[Fixed]-Django: disable PREPEND_WWW when using ip address instead of domain name

1πŸ‘

βœ…

In general, PREPEND_WWW is a lesser used setting as it is buggy – It does not work properly for host name aliases, ip addresses, or even localhost.
This is an known issue on Django, and looks like it would not be fixed.
Here are the details of the relevant ticket

Like @makaveli points out, nginx or any other web server proxy you might be using would be the right place to do the redirection.

However, if you absolutely have to do it in code, here is one way:
One thing you can do is, Write your own custom middleware which is derived from CommonMiddleware which overrides the process_request.

For example,

must_prepend = settings.PREPEND_WWW and host and not host.startswith('www.')
    redirect_url = ('%s://www.%s' % (request.scheme, host)) if must_prepend else ''

Could be (pseudocode)

must_prepend = False
ip_address_regex = ....
if settings.PREPEND_WWW:
    must_prepend =  host and not re.match(ip_address_regex, host) and not host.startswith('www.')
redirect_url = ('%s://www.%s' % (request.scheme, host)) if must_prepend else ''

And of course, this needs to be well tested out, and it would be your responsibility to update this middleware as the CommonMiddleware implementation changes.

πŸ‘€karthikr

Leave a comment