Works like the PREPEND_WWW setting but, instead of adding, it removes the www.
Usage: In the settings file add the UrlMiddleware to the middleware list and set REMOVE_WWW = True
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | from django.conf import settings
from django import http
from django.utils.http import urlquote
from django.core import urlresolvers
class UrlMiddleware(object):
"""
Middleware for removing the WWW from a URL if the users sets settings.REMOVE_WWW.
Based on Django CommonMiddleware.
"""
def process_request(self, request):
host = request.get_host()
old_url = [host, request.path]
new_url = old_url[:]
if (settings.REMOVE_WWW and old_url[0] and old_url[0].startswith('www.')):
new_url[0] = old_url[0][4:]
if new_url != old_url:
try:
urlresolvers.resolve(new_url[1])
except urlresolvers.Resolver404:
pass
else:
if new_url[0]:
newurl = "%s://%s%s" % (
request.is_secure() and 'https' or 'http',
new_url[0], urlquote(new_url[1]))
else:
newurl = urlquote(new_url[1])
if request.GET:
newurl += '?' + request.GET.urlencode()
return http.HttpResponsePermanentRedirect(newurl)
return None
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.