Google App Engine Python Webapp2 301 redirect from www to non-www domain

天涯浪子 提交于 2019-12-06 20:40:29

I'v made the trick.

class BaseController(webapp2.RequestHandler):
   """
   Base controller, all contollers in my cms extends it
   """

    def initialize(self, request, response):
        super(BaseController, self).initialize(request, response)
        if request.host_url != config.host_full:
            # get request params without domain
            url = request.url.replace(request.host_url, '')
            return self.redirect(config.host_full+url, permanent=True)

config.host_full contains my primary domain without www. Solution is to check request in base controller and made redirect if domain differs.

I've modified a bit @userlond answer to not require extra config value, instead I'm using regex:

import re
import webapp2


class RequestHandler(webapp2.RequestHandler):
    def initialize(self, request, response):
        super(RequestHandler, self).initialize(request, response)
        match = re.match('^(http[s]?://)www\.(.*)', request.url)
        if match:
            self.redirect(match.group(1) + match.group(2), permanent=True)

Perhaps this is a simpler way using the default get() request. Please enhance the regex if it is possible for the url to have www in places like query params.

import re
import webapp2


class MainHandler(webapp2.RequestHandler):
    def get(self):
        url = self.request.url

        if ('www.' in url):
            url = re.sub('www.', '', url)
            return self.redirect(url, permanent=True)

        self.response.write('No need to redirect')

app = webapp2.WSGIApplication([
    ('/', MainHandler)
], debug=False)

A solution where you don't need to modify your main application and which also works with static files is to create a service which runs on www. For that create the following files:

www.yaml:

runtime: python27
api_version: 1
threadsafe: yes
service: www

handlers:
- url: /.*
  script: redirectwww.app

redirectwww.py:

import webapp2

class RedirectWWW(webapp2.RequestHandler):
  def get(self):
    self.redirect('https://example.com' + self.request.path)

app = webapp2.WSGIApplication([
  ('.*', RedirectWWW),
])

dipatch.yaml:

dispatch:
  - url: "www.example.com/*"
    service: www

Then deploy with gcloud app deploy www.yaml dispatch.yaml.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!