PermanentRedirectMiddleware

 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. simple DomainsAliasMiddleware by matrix 5 years ago
  2. SiteRedirectMiddleware by jezdez 5 years, 8 months ago
  3. URL redirects middleware by gonz 6 years, 4 months ago
  4. Redirect Multiple Domains to a Single Domain by rpoulton 6 years, 6 months ago
  5. Decorator to modify reverse() to render SSL urls by AndrewIngram 4 years, 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 :)

#

(Forgotten your password?)