Sign up ×
Webmasters Stack Exchange is a question and answer site for pro webmasters. It's 100% free, no registration required.

The settings

I have the following .htaccess rule

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

This works great to redirect any subdomain that is not valid (www or de) to the www subdomain.

I have seen solution, but they only depend on single domain sites.

I have multiple domains:

which all serve their own brand of site.

Now I have the .htaccess rule that is mentioned above and it works beautifully if someone types in it redirects to

The problem

If someone types in, it redirects to and if someone types in, it redirects to

The question

How can I make it so that it redirects to And to

I need an domain insensitve solution because more domains will be added in the future.

share|improve this question

1 Answer 1

up vote 3 down vote accepted

To redirect using the sub-domain as a parameter:

# HTTP 301 Redirect test.*.net -> www.*.net
RewriteCond %{HTTP_HOST} ^test.([^.]+).net$ [NC]
RewriteRule (.*)$1 [R=301,L)

# HTTP 301 Redirect test.*.com -> www.*.com
RewriteCond %{HTTP_HOST} ^test.([^.]+).com$ [NC]
RewriteRule (.*)$1 [R=301,L)

If you also want to redirect when there's no subdomain (e.g. to the main website using the www. subdomain (

# HTTP 301 Redirect *.net -> www.*.net
RewriteCond %{HTTP_HOST} ^([^.]+).net$ [NC]
RewriteRule (.*)$1 [R=301,L)

# HTTP 301 Redirect *.net -> www.*.net
RewriteCond %{HTTP_HOST} ^([^.]+).com$ [NC]
RewriteRule (.*)$1 [R=301,L)

If you're trying to achieve a lot with your .htaccess files you may find it helps to test your conditions and how they affect URL rewriting on the htaccess Made-With-Love website.

In case this is where you struggled, it is always worth remembering that in .htaccess, parameters prefixed with percent symbols (e.g. %1) reference values from the last matched RewriteCond expression, normally values that have been marked as being of interest by being surrounded in brackets (), and parameters prefixed with dollar symbols (e.g. $1) reference values in the RewriteRule expression, normally values that are automatically assigned by Apache and relating to the URL.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.