Redirect Multiple Domains to a Single Domain

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from django.http import HttpResponseRedirect

class ValidateHostMiddleware(object):
    """
    In Apache's httpd.conf, you may have ServerName set to mysite.com.au along 
    with a number of aliases: mysite.com, mysite.net, my-site.com etc.

    This middleware redirects any request that isn't for mysite.com.au to that 
    domain, helping with SEO and brand recognition.
    """
    def process_request(self, request):
        if not request.META['HTTP_HOST'].endswith('mysite.com.au'):
            return HttpResponseRedirect('http://www.mysite.com.au/')

More like this

  1. URL redirects middleware by gonz 4 years, 1 month ago
  2. SSL Middleware for Webfaction by parlar 4 years, 8 months ago
  3. pycallgraph by roppert 3 years ago
  4. Mobilize your Django site by stevena0 2 years, 10 months ago
  5. simple DomainsAliasMiddleware by matrix 2 years, 10 months ago

Comments

arne (on October 3, 2007):

Wouldn't it be "cleaner" to do this in the webserver's configuration?

I use something like this in my .htaccess:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.mydomain\.de$
RewriteRule ^(.*)$ http://www.mydomain.de/$1 [L,R=301]

this redirects every request where HTTP_HOST is not www.mydomain.de to www.mydomain.de and even keeps the path after the domain.

#

bartTC (on August 18, 2008):

Or redirecting without RewriteEngine:

<VirtualHost>
  ServerName example.com
  RedirectPermanent / http://example.net/
</VirtualHost>

#

vizualbod (on May 30, 2009):

In some scenarios it would be better to use server config for this. E.g. if you want to use front-end server to serve static files without touching Django, those static files would be still available on all domains.

My frontend server is Nginx therefore I use this:

server {
        listen 80;
        server_name vizualbod.com *.vizualbod.com;
        if ($host != 'vizualbod.com'){
            rewrite  ^/(.*)$  http://vizualbod.com/$1  permanent;
            }
        root /sites/vizualbod.com;
        include proxy;
        }

#

(Forgotten your password?)