-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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