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/')
Comments
Wouldn't it be "cleaner" to do this in the webserver's configuration?
I use something like this in my .htaccess:
this redirects every request where HTTP_HOST is not www.mydomain.de to www.mydomain.de and even keeps the path after the domain.
#
Or redirecting without RewriteEngine:
#
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:
#