views:

26

answers:

2

Hi,

We have a domain name with various TLDs.

Let's use example.com as our main URL, and we redirect example.biz, example.net, example.org to example.com.

We had the following in .htaccess file and it worked very well:

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

You notice that any non-www will be redirected to www.

However, we just added a subdomain: str.example.com, and in order to make it accessible, we had to comment out the above rules.

I hope someone can help us to write the rules that will redirect:

  1. non-www and non-str to www
  2. non-.com TLDs to .com

Several cases to make my means clear:

  1. example.com -> www.example.com
  2. example.net -> www.example.com
  3. abc.example.com -> www.example.com
  4. str.example.com -> str.example.com
  5. str.example.org -> str.example.com

Thank you very much.

A: 

Try these rules:

RewriteCond %{HTTP_HOST} ^([^/.]+)\.example\.[^/.]+$
RewriteCond %1 !^(www|str)$
RewriteRule ^ http://www.example.com%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTP_HOST} ^([^/.]+)\.example\.([^/.]+)$
RewriteCond %2 !=com
RewriteRule ^ http://%1.example.com%{REQUEST_URI} [L,R=301]
Gumbo
+1  A: 

This is a bit more convoluted, but it saves you a potential extra redirect:

RewriteEngine On

RewriteCond %{HTTP_HOST} !^(www|str)\.        [NC,OR]
RewriteCond %{HTTP_HOST} !\.com$              [NC]
RewriteCond %{HTTP_HOST}  (.*?)\.[A-Z]+$      [NC]
RewriteCond %1            ^(([^.]+)\.)?example$
RewriteCond %2            ^(str)              [OR]
RewriteCond www           ^(www)
RewriteRule ^ http://%1.example.com%{REQUEST_URI} [R=301,L]

Note that it also only expects you to have a single TLD, so example.co.uk wouldn't work here for example. That wasn't one of your examples though, so I didn't attempt to account for it.

Tim Stone
What are the %1 and %2 in the fourth and fifth Cond? The values between parentheses from the previous rules?
Litso
@Litso - Yeah, they're backreferences to the previous positively matched `RewriteCond` test pattern. So `%1` is the capture `(.*?)`, and `%2` is the capture `([^.]+)` from the two respective previous `RewriteCond` statements.
Tim Stone
ah, from the positively matched patterns, that explains the part I didn't grasp. learned yet another thing :)
Litso
Thank you, Tim.If we were to have another subdomain, is it safe to assume that we can change the first cond to RewriteCond %{HTTP_HOST} !^(www|str|def)\. [NC,OR]and the fifth cond to RewriteCond %2 ^(str|www) [OR]?Thanks again.PS. sorry for the editing
@user173457 - No problem. As for your question, I think you meant `(str|def)` for the second `RewriteCond`, but yep, doing just that should allow whatever other subdomains that you might add.
Tim Stone