I have an application built on gae. I use python with webapp2 framework. I need to make 301 redirect from www.my-crazy-domain.com to my-crazy.domain.com so to eliminate www and not-www doubles in search results.
Does anybody have ready-to-use solution? Thanks for any help!
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
.
来源:https://stackoverflow.com/questions/26332234/google-app-engine-python-webapp2-301-redirect-from-www-to-non-www-domain