[Django]-Redirect all requests for www. to root domain

0👍

Solved with this:

from django.http import HttpResponsePermanentRedirect

class WWWRedirectMiddleware(object):
    def process_request(self, request):
        if request.META['HTTP_HOST'].startswith('www.'):
            return HttpResponsePermanentRedirect('http://example.com')

10👍

Create your own middleware in [PROJECT_NAME]/middleware.py, like so:

from django.conf import settings
from django.http import HttpResponsePermanentRedirect
from django.utils.deprecation import MiddlewareMixin


class RemoveWWWMiddleware(MiddlewareMixin):
    """
    Based on the REMOVE_WWW setting, this middleware removes "www." from the
    start of any URLs.
    """
    def process_request(self, request):
        host = request.get_host()
        if settings.REMOVE_WWW and host and host.startswith('www.'):
            redirect_url = '%s://%s%s' % (
                request.scheme, host[4:], request.get_full_path()
            )
            return HttpResponsePermanentRedirect(redirect_url)

Then, in your project’s settings.py:

  • Add REMOVE_WWW = True
  • And add [PROJECT_NAME].middleware.RemoveWWWMiddleware to the MIDDLEWARE list, after Django’s SecurityMiddleware and preferably before Django’s Common Middleware.
  • Also, of course, make sure you haven’t set PREPEND_WWW = True

This middleware is based on Django’s CommonMiddleware.

Leave a comment