Question

Is it possible to have a generic / multi-domain httpd.conf line that will redirect any non-www request to its www equivalent?

By generic, I mean something that does not rely on hardcoded domain name, ie.

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

I really don't want to edit httpd.conf every time I have another website added/removed from my server, esp. that websites are added/removed dynamically!

Was it helpful?

Solution

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]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top