Google-app-engine – How to redirect all URLs with Google App Engine

google-app-engineyaml

How do I configure the app.yaml file to redirect all URLs to another URL? For example I want http://test.appspot.com/hello or http://test.appspot.com/hello28928723 to redirect to http://domain.com.

I am only serving static files at the moment. Here is my app.yaml file:

application: testapp
version: 1
runtime: python
api_version: 1

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

- url: /
  static_dir: static

Best Answer

Webapp2 has a built-in redirect handler

No need to roll your own handler; webapp2 already comes with one.

application = webapp2.WSGIApplication([
    webapp2.Route('/hello', webapp2.RedirectHandler, defaults={'_uri':'http://domain.com'}),
    webapp2.Route('/hello28928723', webapp2.RedirectHandler, defaults={'_uri':'http://domain.com'}),
], debug=False)

The _uri argument is what the RedirectHandler class uses to define the destination. It took a lot of Google Fu to find the documentation on this but it works flawlessly in my app.

Update:

I assumed you're aware of this but you need to change your catch-all route from:

- url: /
  static_dir: static

To (python27 version):

- url: /.*
  script: main.application

Or: (pre python27 version)

- url: /.*
  script: main.py

main.py is the file containing the request handler + routes.

Note: There is no static-only way to handle redirects on GAE because of the nature of static files. Basically, there's no way to do a redirect in app.yaml alone.

Related Topic