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)