The mod_rewrite documentation has all the information you need, but there is a lot to read. There are two parts to what you want: first, you need to match any domain not starting with www.
; then, you need to prefix www.
to the current URL.
For the first part, there's this (which applies to both RewriteCond
and RewriteRule
):
You can prefix the pattern string with a '!' character (exclamation mark) to specify a non-matching pattern.
So "hostname doesn't begin www." could be tested like this:
RewriteCond %{HTTP_HOST} !^www\. [NC]
For the second part, there's this:
In addition to plain text, the Substition string can include [...] server-variables as in rule condition test-strings (%{VARNAME})
So the actual redirect can be made generic like this:
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [L,R=301]
Incidentally, it's also possible to do the opposite (redirect everything to not have the www.
) because RewriteRule
substitutions can also use this:
back-references (%N) to the last matched RewriteCond pattern
So you could capture everything in the hostname after the www.
and use that as the target of the rule:
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]