在Google App Engine中实现HTML 301重定向

0 投票
1 回答
768 浏览
提问于 2025-04-17 14:42

我在谷歌的App Engine上用Python托管一个网站。我有不同的页面,放在不同的文件夹里。我想知道怎么从比如说:“www.example.com/page”进行重定向。当我不在“page”后面加一个“/”时,就会出现“404未找到”的错误。我该如何修改我的重定向脚本来解决这个问题?这是我的app.yaml:

    application: example-app
    version: 4
    runtime: python 
    api_version: 1

    handlers:
    - url: (.*)/
      static_files: static\1/index.html
      upload: static/index.html

    - url: /
      static_dir: static



    - url: /apps/(.*\.apk)
      mime_type: application/vnd.android.package-archive
      static_files: static/apps/\1
      upload: static/apps/(.*\.apk)

    - url: (.*)/apps
      script: directory.py

    - url: /comingsoon
      script: DirecotryHandler.py

    - url: /directory
      script: DirecotryHandler.py

这是我的directoryhandler.py:

    import os
    from google.appengine.ext import webapp
    from google.appengine.ext.webapp.util import run_wsgi_app

    class DirecotryHandler(webapp.RequestHandler):
    def get(self, tail):
    if tail == î:
    self.redirect(ë/directory/í, permanent=True)
    #TODO: respond to ì/directory/î request

    def head(self, tail):
    if tail == î:
    self.redirect(ë/directory/í, permanent=True)
    #TODO: respond to ì/directory/î request

    application = webapp.WSGIApplication(
    [
    (r'^/directory(/?)$', DirectoryPage),
    ])

    def main():
    run_wsgi_app(application)

    if __name__ == ì__main__î:
    main()

我该如何编辑我的DirectoryHandler.py来处理301重定向?提前谢谢你的帮助!

1 个回答

0

其实,是你的浏览器在处理301重定向。你的代码缺少了一个路由 (r'^/comingsoon$', DirecotryHandler),,这个路由是用来生成301重定向的。

当你的浏览器访问 www.example.com/comingsoon 时,你的DirecotryHandler类会处理这个请求,并调用 self.redirect("/directory/", permanent=True)。这样就会生成一个301重定向,作为对你浏览器的响应。浏览器看到新的网址 /directory/ 后,会去请求这个网址,这时就会调用你的 DirectoryPage 类。

撰写回答