Ticket #12662: hostname.py

File hostname.py, 1.2 KB (added by robballou, 6 years ago)

Middleware file

Line 
1from django.conf import settings
2from django.utils.http import urlquote
3from django import http
4
5class EnforceHostnameMiddleware(object):
6    """
7    Enforce the hostname per the ENFORCE_HOSTNAME setting in the project's settings
8   
9    The ENFORCE_HOSTNAME can either be a single host or a list of acceptable hosts
10    """
11    def process_request(self, request):
12        """Enforce the host name"""
13        try:
14            if not settings.ENFORCE_HOSTNAME:
15                # enforce not being used, don't do anything
16                return None
17        except AttributeError, e:
18            return None
19       
20        host = request.get_host()
21       
22        # find the allowed host name(s)
23        allowed_hosts = settings.ENFORCE_HOSTNAME
24        if not isinstance(allowed_hosts, list): 
25            allowed_hosts = [allowed_hosts]
26        if host in allowed_hosts:
27            return None
28       
29        # redirect to the proper host name
30        new_url = [allowed_hosts[0], request.path]
31        new_url = "%s://%s%s" % (
32            request.is_secure() and 'https' or 'http',
33            new_url[0], urlquote(new_url[1]))
34        if request.GET:
35            new_url += '?' + request.META['QUERY_STRING']
36
37        return http.HttpResponsePermanentRedirect(new_url)
Back to Top