Multiple domain www-rewrite

Published on January 26th, 2009

A while ago I wrote about how to rewrite non-www requests to www requests. While that solution is solid and has been working for me the past couple of years I came across a related challenge today: rewriting non-www to www requests on multiple domains at the same time.

Why would you want to do that?

There’s only one good reason why you would want do do this: if you’re using a single file system (thus a single .htaccess file) for multiple websites/domains.

RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_HOST} !^www.* [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Enter the code above into your .htaccess file. Now all requests will be rewritten to have the www. prefix. For instance: the request for http://domain.com/directory/filename.html will be rewritten to http://domain.com/directory/filename.html. Independent from the domain request. The %{HTTP_HOST} and %{REQUEST_URI} will get the original domain from the request.

The .htaccess file

The .htaccess file can be found in the root of your website directory (where you also find your index file). If you can’t locate the file it might be hidden; file names starting with a dot are automatically hidden by a some FTP clients. Set your FTP client to show hidden files.

Another reason for the .htaccess file not showing up could be that it doesn’t exist (yet). Just create a new empty file on your server and copy the rewriting code to it.

Be sure to notice that your server needs to have the mod_rewrite module installed and activated.

Reader Comments (5)


February 10th, 2009

Thanks, this is great. Just what I was looking for!

Nick Maloney http://www.prolucid.com

May 1st, 2009

Thank you for posting this! It was exactly what I needed.

Jack Bakkin

November 16th, 2009

Thanks a lot for the article. I really was looking for this. Found some but they exactly didn’t specify most of the stuff I needed. Cheers

Lyle and Scott

December 29th, 2009

Appreciate the information provided. Honestly I was looking all over for something like this and found absolutely nothing. Thanks again. Cheers

Green Building http://www.thegreenbuildingsite.co.uk

January 6th, 2010

Great. I was looking for similar code. Thanks

Leave a comment