Remove www from URLs in Django

1 December 2009

In building the new, I wanted to remove www. from all of our URLs. Why? For one, www. is unnecessary. It's a vestigial organ of the internet from the days when you might have just as frequently visited a domain via ftp, telnet or newsgroup as you did over http. The other primary reason is that many search engines treat links to as a different link that By redirecting all www. requests with a 301 status code, to their non www. equivalents, you combine the two disparate rankings into one.

While Django offers a PREPEND_WWW setting to force URLs to have www. in them, it does not and will not offer the reverse functionality. However, a simple piece of middleware can do the trick. Just add the following code to your file (or wherever you keep your custom middleware):

Then add middleware.RemoveWWW to your MIDDLEWARE_CLASSES setting. That's all there is to it. By using the built in build_absolute_uri method we ensure that any parameters are passed along as well as preserving https if it's in use.

View the source code on Github