SysAdmin

Django – Redirect non-www to www URLs

JJ
Jobin Joseph · Founder and CEO
·Published 24 November 2012·1 min read

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] 
Jobin Joseph
Jobin Joseph, Founder and CEO
5x AWS Certified, ISO 27001:2022 Lead Implementer, 17+ years building cloud infrastructure for regulated industries.
About Jobin →

Reading this because your AWS bill or uptime is a problem?

30 minutes, direct with the founder, no sales pitch: one specific recommendation for your AWS workload.

Book a free 30-minute review
30 min Free Consultation →