To redirect non-www to www we often see this in .htaccess:
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.example\.com [NC]
RewriteRule ^(.*) http://www.example.com/%{REQUEST_URI} [R=301,NE,L]
The problem is when we also have subdomains: http://wiki.example.com
will be redirected to http://www.wiki.example.com
A workaround is to add each subdomains to the regular expression. Not very nice.
So I redirect from non-www to www with this:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^(.*) http://www.example.com/%{REQUEST_URI} [R=301,L]
The condition is negated, and we can then safely use subdomains.
My question: how to have a "generic" .htaccess? i.e without giving the domain name? (less admin work, allow to have several domains pointing to the same directory, etc). I found something promising:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(?!www\.)(.+) [NC]
RewriteRule ^(.*) http://www.%1/$1 [R=301,NE,L]
But once again http://wiki.example.com
will be redirected to http://www.wiki.example.com
.
I don't figure how to add the www only when no subdomain is specified.
UPDATE
Thanks to people who gave answers, I finally used that:
RewriteEngine on
RewriteCond %{HTTP_HOST} !\..+\.
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]