Login

simple DomainsAliasMiddleware

Author:
matrix
Posted:
March 30, 2009
Language:
Python
Version:
1.0
Tags:
middleware redirect domain
Score:
1 (after 1 ratings)

Permit to redirect desired domain name to the 'domain' of Site app. Useful if you have different domains name for the same website.

1. Add to your settings DOMAINS_ALIAS like this:

DOMAINS_ALIAS = (
    'my-second-domain.com',
    'www.my-second-domain.com',
    'third-domain.com',
    'www.third-domain.com',
)

notice: all these domains are redirected to the domain db entry of Site ID.

2. add all these domains to ServerAlias directive in your vhost apache configuration.

3. enable the middleware by adding to your MIDDLEWARE_CLASSES:

MIDDLEWARE_CLASSES = (
    ...
    'utils.middleware.domainsalias.DomainsAliasMiddleware',
    ...
)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from django.conf import settings
from django.http import HttpResponseRedirect
from django.contrib.sites.models import Site

class DomainsAliasMiddleware:
    '''
    Redirect to Site 'domain' if target domain found in DOMAINS_ALIAS
    '''
    def process_request(self, request):
        target_domain = request.META.get("HTTP_HOST", "localhost")
        if hasattr(settings, 'DOMAINS_ALIAS'):
            for domain in settings.DOMAINS_ALIAS:
                if domain == target_domain:
                    return self._redirect(request)
        return None

    def _redirect(self, request):
        if request.path == "": request.path = "/"
        newurl = "%s://%s%s" % (request.is_secure() and 'https' or 'http', \
                Site.objects.get_current().domain, request.path)
        if request.GET:
            newurl += '?' + request.GET.urlencode()
        return HttpResponseRedirect(newurl)

More like this

  1. PermanentRedirectMiddleware by marinho 6 years, 10 months ago
  2. SSL Redirect Middleware by zbyte64 6 years, 10 months ago
  3. ScriptPrefixMiddleware by shellsage 5 years, 8 months ago
  4. Super User Conditional Page Exception Reporting by zbyte64 6 years, 10 months ago
  5. HTML 5 Firefox 2 Hack by epicserve 5 years, 6 months ago

Comments

Please login first before commenting.