Django – Redirect non-www to www URLs

24. November 2012 SysAdmin 0

Guys,

Today I had a bad time with a non-www to www redirect on a Django site.

Since I had worked many PHP applications, I tried Apache redirect and mod-rewrite options with no luck. After some googling, I came to know that the mod-rewrite option won’t work with Django applications.

The only solution is to give the following in the “server_settings.py” configuration file of the Django application.

PREPEND_WWW = True

Reload Apache, then try the URL.

After enabling this your site will automatically redirect from example.com to www.example.com for any URLs.

FYI: The normal mod_rewrite option is,

Redirect non-www to www:

RewriteEngine on
rewritecond %{http_host} ^domain.com [nc]
rewriterule ^(.*)$ http://www.domain.com/$1 [r=301,nc]

Redirect www to non-www:

RewriteEngine on
rewritecond %{http_host} ^www.domain.com [nc]
rewriterule ^(.*)$ http://domain.com/$1 [r=301,nc]


Leave a Reply

Your email address will not be published. Required fields are marked *