Changeset - 55a10b750b6a
[Not reviewed]
0 2 0
Christopher Neugebauer - 7 years ago 2017-08-17 15:09:21
chrisjrn@gmail.com
Adds a middleware to canonicalise the hostname
2 files changed with 25 insertions and 1 deletions:
0 comments (0 inline, 0 general)
pinaxcon/middleware.py
Show inline comments
...
 
@@ -2,12 +2,35 @@ import re
 
import warnings
 

	
 
from django import http
 
from django.conf import settings
 
from django.utils.deprecation import MiddlewareMixin
 

	
 
class CanonicalHostMiddleware(MiddlewareMixin):
 
    """ Redirects to a canonical host if the current host is not the canonical
 
    host. """
 

	
 
    response_redirect_class = http.HttpResponsePermanentRedirect
 

	
 
    def process_request(self, request):
 

	
 
        canonical_host = getattr(settings, "CANONICAL_HOST", None)
 

	
 
        if not canonical_host:
 
            return
 

	
 
        host = request.get_host()
 

	
 
        if host == canonical_host:
 
            return
 

	
 
        path = request.get_full_path()
 
        redirect_url = ('%s://%s%s' % (request.scheme, canonical_host, path))
 
        return self.response_redirect_class(redirect_url)
 

	
 

	
 
class UnprependWWWMiddleware(MiddlewareMixin):
 
    """ Unprepends www if necessary. """
 

	
 
    response_redirect_class = http.HttpResponsePermanentRedirect
 

	
 
    def process_request(self, request):
pinaxcon/settings.py
Show inline comments
...
 
@@ -20,12 +20,13 @@ UNPREPEND_WWW = bool(os.environ.get("DJANGO_UNPREPEND_WWW", False))
 
# HEROKU: Update database configuration with $DATABASE_URL.
 
import dj_database_url
 
db_from_env = dj_database_url.config()
 
DATABASES['default'].update(db_from_env)
 

	
 
ALLOWED_HOSTS = [".localhost", ".herokuapp.com", ".northbaypython.org"]
 
CANONICAL_HOST = os.environ.get("DJANGO_CANONICAL_HOST", None)
 

	
 
# Local time zone for this installation. Choices can be found here:
 
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
 
# although not all choices may be available on all operating systems.
 
# On Unix systems, a value of None will cause Django to use the same
 
# timezone as the operating system.
...
 
@@ -131,14 +132,14 @@ MIDDLEWARE_CLASSES = [
 
    "django.contrib.auth.middleware.AuthenticationMiddleware",
 
    "django.contrib.auth.middleware.SessionAuthenticationMiddleware",
 
    "django.contrib.messages.middleware.MessageMiddleware",
 
    "reversion.middleware.RevisionMiddleware",
 
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
 
    "ssl_redirect.middleware.SSLRedirectMiddleware",
 
    "pinaxcon.middleware.CanonicalHostMiddleware",
 
    "pinaxcon.middleware.UnprependWWWMiddleware",
 

	
 
]
 

	
 
ROOT_URLCONF = "pinaxcon.urls"
 

	
 
# Python dotted path to the WSGI application used by Django's runserver.
 
WSGI_APPLICATION = "pinaxcon.wsgi.application"
0 comments (0 inline, 0 general)