Force www. prefix using .htaccess mod_rewrite

Forcing a redirect to “www.” on a website using .htaccess and mod_rewrite is easy.

Create a .htaccess file with this in it:

RewriteEngine on
RewriteCond %{HTTP_HOST} !^www.yourdomain.com$
RewriteRule ^(.*)$ http://www.yourdomain.com/$1 [R=301]

If you need to combine this redirect with some other mod_rewrite rules, then try putting the redirect at the very end like so:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php [L,QSA]
RewriteCond %{HTTP_HOST} !^www.yourdomain.com$
RewriteRule ^(.*)$ http://www.yourdomain.com/$1 [R=301]

Going one step further you can redirect all requests except those for certain files like so:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php [L,QSA]
RewriteCond %{HTTP_HOST} !^www.yourdomain.com$
RewriteCond %{REQUEST_FILENAME} !some_script.php
RewriteRule ^(.*)$ http://www.yourdomain.com/$1 [R=301]

That
way requests to http://yourdomain.com/some_script.php will not be prefixed with www.

Leave a Reply

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