Skip to content

Instantly share code, notes, and snippets.

@macedd
Created March 2, 2020 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save macedd/f08beefe1eeac5067297330350f64a8f to your computer and use it in GitHub Desktop.
Save macedd/f08beefe1eeac5067297330350f64a8f to your computer and use it in GitHub Desktop.
Flask Ensure Domain (redirect) Middleware

The middleware helps ensure a site domain. Useful when the main domain change and we want to keep links and user attending the new domain.

There are a few settings via environment variables, state bellow.

  • FLASK_ENV (required) has to be production otherwise will not apply redirection;
  • SITE_DOMAIN (required) the principal domain to redirect to;
  • PRODUCTION_DOMAINS (optional) to list your available domains (comma separated). When supplied will only redirect from those domains. Useful for pre-production domains.
import flask
import middleware
app = flask.create_app(os.path.dirname(__file__))
app.wsgi_app = middleware.EnsureDomainMiddleWare(app.wsgi_app)
import os
from flask import redirect
class EnsureDomainMiddleWare(object):
'''Simple WSGI middleware'''
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
if self.is_production(environ):
# ensure required site domain
site_domain = os.environ.get('SITE_DOMAIN')
if site_domain and site_domain != environ['HTTP_HOST']:
redirected_uri = '//%s%s?domain=%s' % (site_domain, environ.get('REQUEST_URI', environ.get('PATH_INFO', '')), environ.get('HTTP_HOST'))
response = redirect(redirected_uri, code=301)
return response(environ, start_response)
return self.app(environ, start_response)
def is_production(self, environ):
production_env = os.environ.get('FLASK_ENV') == 'production'
production_domain = True
domains = os.environ.get('PRODUCTION_DOMAINS', "").split(',')
if len(domains):
production_domain = environ.get('HTTP_HOST') in domains
return production_env and production_domain
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment