Skip to content

Instantly share code, notes, and snippets.

@jacobwegner
Last active January 28, 2016 00:02
Show Gist options
  • Save jacobwegner/79d6019bc35ede87c5bf to your computer and use it in GitHub Desktop.
Save jacobwegner/79d6019bc35ede87c5bf to your computer and use it in GitHub Desktop.
Django Middleware to redirect to a root domain
import re
from django import http
from django.utils import six
from django.utils.http import urlquote
WWW_PATTERN = re.compile(r"www\.")
class RootDomainRedirectMiddleware(object):
"""
Inspired by Django"s CommonMiddleware, performs the opposite of
PREPEND_WWW by stripping www from the front of a host
"""
response_redirect_class = http.HttpResponsePermanentRedirect
def process_request(self, request):
"""
Remove WWW from the hostname
"""
host = request.get_host()
old_url = [host, request.path]
new_url = old_url[:]
if (old_url[0] and re.match(WWW_PATTERN, old_url[0])):
new_url[0] = re.sub(WWW_PATTERN, "", old_url[0])
if new_url == old_url:
# No redirects required.
return
if new_url[0]:
newurl = "%s://%s%s" % (
request.scheme,
new_url[0], urlquote(new_url[1]))
else:
newurl = urlquote(new_url[1])
if request.META.get("QUERY_STRING", ""):
if six.PY3:
newurl += "?" + request.META["QUERY_STRING"]
else:
# `query_string` is a bytestring. Appending it to the unicode
# string `newurl` will fail if it isn"t ASCII-only. This isn"t
# allowed; only broken software generates such query strings.
# Better drop the invalid query string than crash (#15152).
try:
newurl += "?" + request.META["QUERY_STRING"].decode()
except UnicodeDecodeError:
pass
return self.response_redirect_class(newurl)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment