3

I need to redirect all requests coming from www.mysite.com to mysite.com

I have found the solution in rails, but how can I do that in Django/Python?

The only solution I could find, which was posted by a moderator on GoDaddy was the above. Seems like I cannot resolve this kind of problem through the DNS Manager of GoDaddy.

beddamadre
  • 1,583
  • 2
  • 19
  • 40

2 Answers2

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.

Jeff Bowen
  • 5,904
  • 1
  • 28
  • 41
  • 2
    This should be the accepted answer - I can confirm that this solution works perfectly with Django==2.0.2. Thanks a lot, Jeff! I was having trouble doing this from the DNS side. – Jihoon Baek Aug 27 '18 at 20:43
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')
beddamadre
  • 1,583
  • 2
  • 19
  • 40