How to redirect non-www to www URL’s using htaccess?

This is a more generic solution, because it can be used with any domain name without having to specify the specific domain name in each .htaccess:

# Redirect non-www to www:
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

The contrary is also possible (www to non-www):

# Redirect www to non-www
RewriteCond %{HTTP_HOST} ^www\.(.*) [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

Leave a Comment