Google App Engine Redirect Naked Domain And Appspot To WWW

December 20, 2017

When I setup Google App Engine a few years ago, it doesn’t support naked domain directly where it would redirect naked domain to www. As I tested on 2017-12-12, the previous statement is no longer accurate.

Once Google App Engine custom domains is setup, it can be accessed via 3 domains:

  • mydomain.com (naked domain)
  • www.mydomain.com (www)
  • projectid.appspot.com (appspot domain)

If you want to redirect both naked naked and appspot domain to www, you have to do it via application code.

The following is an example using flask.

from flask import Flask, request, redirect

app = Flask(__name__)

@app.before_request
def handle_before_request():
    # prevent cronjob redirect error
    if 'AppEngine-Google' not in request.user_agent.string:
        if request.host in ['mydomain.appspot.com', 'mydomain.com']:
            url = request.url.replace(request.host, 'www.mydomain.com')
            return redirect(url, code=301)
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.