Google App Engine Python Webapp2 301从www重定向到非www域

问题描述 投票:1回答:4

我有一个建立在gae上的应用程序。我使用python和webapp2框架。我需要将301重定向从www.my-crazy-domain.com重定向到my-crazy.domain.com,以便在搜索结果中消除www和not-www双打。

有没有人有现成的解决方案?谢谢你的帮助!

python google-app-engine seo webapp2 no-www
4个回答
5
投票

我成功了。

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的主域名。解决方案是检查基本控制器中的请求,如果域不同则进行重定向。


0
投票

我已经修改了一点@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)

0
投票

也许这是使用默认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)

0
投票

您不需要修改主应用程序以及也可以使用静态文件的解决方案是创建一个在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进行部署。

© www.soinside.com 2019 - 2024. All rights reserved.