7
votes

I've seen the trick on Apache's rewrite guide on how to redirect non-www requests to www requests:

RewriteCond %{HTTP_HOST}   !^www\.example\.com [NC]
RewriteCond %{HTTP_HOST}   !^$
RewriteRule ^/(.*)         http://www.example.com/$1 [L,R]

Which redirects all requests for example.com to www.example.com.

But how do I add in that I want requests from example1.com, www.example1.com, example2.com, www.example2.com, etc. to redirect to www.example.com?

EDIT:

Here's the solution:

RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.example\.com [NC]
RewriteCond %{HTTP_HOST} !^$
RewriteRule ^/?(.*) http://www.example.com/$1 [L,R,NE] 

Slightly different RewriteRule and added 'RewriteEngine on'

1
The R rewrite flag defaults to a 302 response code by default. If you want a 301 instead (which I think you do in most situations), you can do this instead: RewriteRule ^/?(.*) http://www.example.com/$1 [L,R=301,NE] - Ian Dunn
strange, this doesn't work for me or fail service apache2 restart - user1382306

1 Answers

4
votes

But how do I add in that I want requests from example1.com, www.example1.com, example2.com, www.example2.com, etc. to redirect to www.example.com?

You've already done that. Your rewrite rule states "if HTTP_HOST isn't www.example.com (and isn't blank), redirect to www.example.com".

As long as your server is set up to point the other domains at the same directory you're hosting www.example.com out of, you're all set.