How to redirect all URLs with Google App Engine

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.


All you need (replace app-id, http://example.com):

  • app.yaml:

    application: app-id
    version: 1
    runtime: python27
    api_version: 1
    threadsafe: false
    
    handlers:
    - url: /.*
      script: main.py
    
  • main.py:

    from google.appengine.ext import webapp
    from google.appengine.ext.webapp.util import run_wsgi_app
    
    class AllHandler(webapp.RequestHandler):
        def get(self):
            self.redirect("http://example.com", True)
    
    application = webapp.WSGIApplication([('/.*', AllHandler)])
    
    def main():
        run_wsgi_app(application)
    
    if __name__ == "__main__":
        main()
    

you can redirect all requests easily with a python handler. Something like

class FormHandler(webapp.RequestHandler):
  def post(self):
    if processFormData(self.request):
      self.redirect("http://domain.com")