21

How do I configure the app.yaml file to redirect all URLs to another URL? For example I want http://example.appspot.com/hello or http://example.appspot.com/hello28928723 to redirect to http://example.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

7 Answers 7

40

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://example.com'}),
    webapp2.Route('/hello28928723', webapp2.RedirectHandler, defaults={'_uri':'http://example.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.

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.

6
  • 2
    This handles get/post/etc... It's basically the 'proper' way to do a 301 (permanent) redirect in GAE. May 4, 2012 at 17:34
  • It's important to note that apparently App Engine doesn't support redirecting to static files/directories. I couldn't get the redirect to work. I kept getting these errors in my logs: "File referenced by handler not found: main.app". Finally, I found this, which confirmed that static files are not accessible to handlers: stackoverflow.com/questions/8734040/…. Nov 27, 2013 at 19:20
  • @StephenKaiser Technically, it's not a redirect but you could define a new route in app.yaml that points from the old URI to the new one. Due to the architecture and the way static files are handled there's no way to define an actual 301/302 redirect on static files. Feb 4, 2014 at 18:34
  • I think hello28928723 was just an example, he wanted to redirect all requests.
    – Jonny
    Apr 15, 2014 at 1:55
  • @Jonny There's a significant difference between how static and non-static files are handled on GAE. You could add a non-static handle in the list above the static handler specifically to catch just redirects. Either way, it's important to understand how and why static files are handled different in GAE. App.yaml is basically an instruction set for a reverse proxy where all static files are actually stored on a static file cache separately from the non-static files. 302/301 redirects aren't possible until you hit the a http server (ie not the static cache). Dec 15, 2014 at 5:53
9

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()
    
2
5

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://example.com")
2
  • 10
    This answer is incomplete - that code snippet is insufficient on its own to redirect reqeusts. Also, what about get requests? May 1, 2012 at 22:50
  • 1
    @BrianLeathem Just posted a complete example.
    – feklee
    Aug 18, 2013 at 9:50
5

If you want a static-files-only way to do "redirects" then do this:

In the app.yaml, put this as the catch-all, at the end of the file:

-   url: /.*
    static_files: root/redirect.html
    upload: root/redirect.html

Then in the root/redirect.html file, put this:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="refresh" content="0;URL=/" />
        <script>
            location.replace("/");
        </script>
    </head>
    <body></body>
</html>

This example will redirect all unknown URLs to the root (i.e., / ). If you want another URL, just substitute http://example.com in the appropriate places.

4

Here is a python script that will do the redirect:

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

class MainPage(webapp.RequestHandler):
  def get(self, path):
    self.redirect("http://example.com", permanent=True)
  def head(self, path):
    self.redirect("http://example.com", permanent=True)

application = webapp.WSGIApplication(
            [
                (r'^(.*)', MainPage)
            ])

def main():
   run_wsgi_app(application)

if __name__ == "__main__":
    main()
2
  • Note the webapp2 answer provided by @Evan Plaice works, but I was stuck with the older datastore and couldn't use python 2.7. May 1, 2012 at 13:33
  • +1 for posting a solution that's backward compatible with webapp. Nov 27, 2013 at 20:29
-1

The redirect handler for webapp2 (webapp2.RedirectHandler) mentioned in a previous answer will not work for post requests, as it does not contain a post method (see https://github.com/GoogleCloudPlatform/webapp2/blob/master/webapp2.py), so you will need to roll your own python handler if concerned with posts. Something like the following:

import webapp2

class MainPage(webapp2.RequestHandler):


    def post(self):
        self.redirect('http://example.com')


application = webapp2.WSGIApplication([
('/.*', MainPage)
], debug=False)
-1

Riffing off Evan's answer, to redirect all requests you could use regexes to do something like:

import webapp2
from webapp2_extras.routes import RedirectRoute

app = webapp2.WSGIApplication([
     RedirectRoute('/<:.*>', redirect_to='/')
    ], debug=False)

For official docs check out:

https://webapp2.readthedocs.io/en/latest/guide/routing.html

https://webapp2.readthedocs.io/en/latest/api/webapp2.html#webapp2.Route.init

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.