【发布时间】:2014-12-07 13:26:41
【问题描述】:
我有一个基于 gae 的应用程序。我将 python 与 webapp2 框架一起使用。我需要从 www.my-crazy-domain.com 到 my-crazy.domain.com 进行 301 重定向,以消除搜索结果中的 www 和 not-www 双精度.
有人有现成的解决方案吗?感谢您的帮助!
【问题讨论】:
标签: python google-app-engine seo webapp2 no-www
我有一个基于 gae 的应用程序。我将 python 与 webapp2 框架一起使用。我需要从 www.my-crazy-domain.com 到 my-crazy.domain.com 进行 301 重定向,以消除搜索结果中的 www 和 not-www 双精度.
有人有现成的解决方案吗?感谢您的帮助!
【问题讨论】:
标签: python google-app-engine seo webapp2 no-www
您不需要修改主应用程序并且也适用于静态文件的解决方案是创建一个在 www 上运行的服务。为此创建以下文件:
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
然后使用gcloud app deploy www.yaml dispatch.yaml 进行部署。
【讨论】:
也许这是使用默认 get() 请求的一种更简单的方法。如果 URL 可以在查询参数等位置包含 www,请增强正则表达式。
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)
【讨论】:
我修改了一点@userlond 的答案,不需要额外的配置值,而是使用正则表达式:
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)
【讨论】:
我成功了。
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 包含我没有 www 的主域。解决方案是检查基本控制器中的请求,如果域不同则进行重定向。
【讨论】: