Middleware to remove the WWW from the URL

 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

  1. PermanentRedirectMiddleware by marinho 5 years, 9 months ago
  2. django subdomain support for both resolve and reverse. by puppy 3 years, 10 months ago
  3. Localized URLs (www-en) by zeeg 7 years, 1 month ago
  4. Spaceless all HTML pages by matrix 1 year, 4 months ago
  5. Web crawler/bot detection and blocking middleware by haloween 4 years, 3 months ago

Comments

(Forgotten your password?)