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
- Stuff by NixonDash 1 month ago
- Add custom fields to the built-in Group model by jmoppel 3 months, 1 week ago
- Month / Year SelectDateWidget based on django SelectDateWidget by pierreben 6 months, 3 weeks ago
- Python Django CRUD Example Tutorial by tuts_station 7 months ago
- Browser-native date input field by kytta 8 months, 3 weeks ago
Comments
Please login first before commenting.