diff --git a/pinaxcon/middleware.py b/pinaxcon/middleware.py index f0a60b0141375dc77a3f145cc3f408f5e49558e0..b70e96a769b9ee4a9acaad95d48169483e845c3f 100644 --- a/pinaxcon/middleware.py +++ b/pinaxcon/middleware.py @@ -5,6 +5,29 @@ 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. """ diff --git a/pinaxcon/settings.py b/pinaxcon/settings.py index d568f711bd08a5f2f43a43533147b02a6ba89f37..f76a65d22d815d4fc1fe171e5851dde054a83f2a 100644 --- a/pinaxcon/settings.py +++ b/pinaxcon/settings.py @@ -23,6 +23,7 @@ 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 @@ -134,8 +135,8 @@ MIDDLEWARE_CLASSES = [ "reversion.middleware.RevisionMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", "ssl_redirect.middleware.SSLRedirectMiddleware", + "pinaxcon.middleware.CanonicalHostMiddleware", "pinaxcon.middleware.UnprependWWWMiddleware", - ] ROOT_URLCONF = "pinaxcon.urls"