Django – Redirect non-www to www URLs

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.

Bonus: The normal mod_rewrite option for PHP

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] 
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Scroll to Top