Redirect non-www to www in .htaccess

Paul Sanchez picture Paul Sanchez · Aug 21, 2012 · Viewed 420.4k times · Source

I have this in my .htaccess file:

RewriteCond %{HTTP_HOST} ^example.com$
RewriteRule (.*) http://www.example.com$1 [R=301,L]

but whenever I access a file on my root like http://example.com/robots.txt it will redirect to http://www.example.comrobots.txt/.

How can I correct this so that it will redirect correctly to http://www.example.com/robots.txt?

Answer

Randall Hunt picture Randall Hunt · Aug 21, 2012

Change your configuration to this (add a slash):

RewriteCond %{HTTP_HOST} ^example.com$ [NC]
RewriteRule (.*) http://www.example.com/$1 [R=301,L] 

Or the solution outlined below (proposed by @absiddiqueLive) will work for any domain:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

If you need to support http and https and preserve the protocol choice try the following:

RewriteRule ^login\$ https://www.%{HTTP_HOST}/login [R=301,L]

Where you replace login with checkout.php or whatever URL you need to support HTTPS on.

I'd argue this is a bad idea though. For the reasoning please read this answer.