Skip to content

Instantly share code, notes, and snippets.

@pmclanahan
Forked from robballou/hostname_middleware.py
Created August 30, 2011 04:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pmclanahan/1180163 to your computer and use it in GitHub Desktop.
Save pmclanahan/1180163 to your computer and use it in GitHub Desktop.
Django middleware for enforcing a hostname. Using at epio until they provide options for redirects at the loadbalancers.
from django.conf import settings
from django.http import HttpResponsePermanentRedirect
class EnforceHostnameMiddleware(object):
"""
Enforce the hostname per the ENFORCE_HOSTNAME setting in the project's settings
The ENFORCE_HOSTNAME can either be a single host or a list of acceptable hosts
"""
def process_request(self, request):
"""Enforce the host name"""
allowed_hosts = getattr(settings, 'ENFORCE_HOSTNAME', None)
if settings.DEBUG or not allowed_hosts:
return None
host = request.get_host()
# find the allowed host name(s)
if isinstance(allowed_hosts, basestring):
allowed_hosts = [allowed_hosts]
if host in allowed_hosts:
return None
# redirect to the proper host name\
new_url = "%s://%s%s" % (
'https' if request.is_secure() else 'http',
allowed_hosts[0], request.get_full_path())
return HttpResponsePermanentRedirect(new_url)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment