Skip to content

Instantly share code, notes, and snippets.

@mgaitan
Forked from pmclanahan/hostname_middleware.py
Last active April 16, 2017 17:17
Show Gist options
  • Save mgaitan/5afe6535ec34158bb97d9951e1315bff to your computer and use it in GitHub Desktop.
Save mgaitan/5afe6535ec34158bb97d9951e1315bff 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
from django.utils import six
def enforce_hostname(get_response):
"""
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 middleware(request):
import ipdb; ipdb.set_trace()
"""Enforce the host name"""
response = get_response(request)
allowed_hosts = getattr(settings, 'ENFORCE_HOSTNAME', None)
if settings.DEBUG or not allowed_hosts:
return response
host = request.get_host()
# find the allowed host name(s)
if isinstance(allowed_hosts, six.string_types):
allowed_hosts = [allowed_hosts]
if host in allowed_hosts:
return response
# 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)
return middleware
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment