Google App Engine Redirect Naked Domain And Appspot To WWW

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, redirectapp = Flask(__name__)@app.before_requestdef 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)

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.