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 ^(.*)$$1 [L,R=301]

to redirect to

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

Potentially, there could be dozens of versions of, 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]


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.


(which is what PP was saying)
This is going to pick up anything after the example. tho? i.e. would try and re-direct to
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]