Google App Engine Static Website Redirect Trailing Slash

September 29, 2018
Routing directory index page without trailing slash to one with trailing slash

This page is about static website hosting and redirect pages like /about to /about/.

Sadly, redirect configuration is not possible using app.yaml, but it can be used with a combination of coding to achieve the same result.

Edit app.yaml.

handlers:
# file with extensions (longer cache period)
- url: /(.*\.(css|js|woff|woff2|ico|png))
  static_files: www/\1
  upload: www/(.*)
  expiration: "7d"
  secure: always

# file with other extensions (e.g. .html)
- url: /(.*\..*)
  static_files: www/\1
  upload: www/(.*)
  secure: always

# assume file without extensions use default index.html
- url: /(.*)/
  static_files: www/\1/index.html
  upload: www/(.*)/index.html
  secure: always

# home
- url: /
  static_files: www/index.html
  upload: www/index.html
  secure: always

# access without trailing slash
- url: /(.*)
  script: mini.app

Create file mini/__init__.py.

This file will redirect pages like /about to /about/.

from flask import Flask, abort
app = Flask(__name__)

@app.route('/<path:path>/')
def redirect(path):
    # will never reach this code, as /path/ is intercepted at app.yaml
    abort(404)

NOTE: I make use of flask routing feature to redirect pages without trailing slash to one with trailing slash, but you could use other methods which you are comfortable with.

NOTE: Refer to Flask On Google App Engine

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.