Login

PermanentRedirectMiddleware

Author:
marinho
Posted:
July 24, 2008
Language:
Python
Version:
.96
Score:
0 (after 0 ratings)

This is a simple middleware that redirects the exactly URL requested with the correct domain. It is useful when you have more than one domain (most of cases with "www." or IP) to access a website.

To make it works, download the snippet file as the name "permanent_redirect.py" and add its path as the first item in MIDDLEWARE_CLASSES setting in settings.py.

Later you must inform a setting called HTTP_HOST_DOMAIN with the correct domain.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
from django.conf import settings
from django.http import HttpResponsePermanentRedirect

class PermanentRedirectMiddleware(object):
    def process_request(self, request):
        if hasattr(settings, 'HTTP_HOST_DOMAIN') and\
           'HTTP_HOST' in request.META and \
           request.META['HTTP_HOST'] != settings.HTTP_HOST_DOMAIN:
            return HttpResponsePermanentRedirect("http%s://%s%s"%(
                request.is_secure() and 's' or '',
                settings.HTTP_HOST_DOMAIN,
                request.get_full_path(),
                )
            )

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

mk (on July 25, 2008):

Here is something better for you which even works with http/https:

class ForceDomainMiddleware(object):

    def process_request(self, request):
            domain = getattr(settings, 'FORCE_DOMAIN', None)

            if not domain:
                    return

            if request.META['HTTP_HOST'] != domain:
                    target = 'http%s://%s%s' % (
                            request.is_secure() and 's' or '',
                            domain,
                            request.get_full_path())
                    return HttpResponsePermanentRedirect(target)

#

marinho (on July 29, 2008):

Fixed with mk good ideas :)

#

Please login first before commenting.