Using htaccess to redirect requests from non-www to www (but with a twist)

Tag: .htaccess Author: h725bin Date: 2009-11-11

I'm currently using htaccess to force all requests to use www. So:

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

to redirect example.com/page to www.example.com/page.

However, this htaccess file is being used by several international versions of example.com. What code do I want that can also do the following:

example.de/page -> www.example.de/page and example.co.uk/page -> www.example.co.uk/page etc.

Potentially, there could be dozens of versions of example.com, so I'm looking to avoid having to remember to edit htaccess every time we add a new country.

Have you tried a capturing match on the regexp in your RewriteCond and referring to that match in your RewriteRule?

Other Answer1

You can use server variables in your substition, so this should be doable with

RewriteRule ^(.*)$ http://www.${HTTP_HOST}/$1 [L,R=301]

comments:

I like it, succinct!

Other Answer2

Right: think I've actually got it cracked. (Or at least it looks like it works):

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

seems to do the trick.

comments:

(which is what PP was saying)
This is going to pick up anything after the example. tho? i.e. example.abc would try and re-direct to www.example.abc
But PP doesn't deserve the credit because he only put in 10% inspiration, not 90% perspiration ;)

Other Answer3

Test if the current host name does not begin with www. and add it if missing:

RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]