Force hostname with Django middleware e.g for Heroku

You have an app on:

your-app.heroku.com

And you created a c-name

your-app.com to your-app.heroku.com

 

But you want it to be available on both urls (ALLOWED_HOSTS = ['your-app.heroku.com', 'your-app.com'])
Because you want to use the handy $ heroku open command.

However you hate to see the .heroku.com address.

Hence this middleware that forces the host.

ENFORCE_HOSTNAME = ['your-app.com', ]

 

# project/middelware.py
# place it on the top of your settings.MIDDLEWARE_CLASSES

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)