1

I have multiple domains with different TLDs (.com, .net, .org) but what's in front of the TLD is the same.

I would like to redirect the .net and .org to .com, without www:

  1. www.<domain>.net, <domain>.net
  2. www.<domain>.org, <domain>.org
  3. www.<domain>.com

to be redirected to:

  • <domain>.com (without www)

<domain> is dynamic and I don't want to hard-code it in .htaccess.

For redirecting www to non-www I use the following condition:

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

I would like to extend this condition to include also the TLD condition and to achieve the 301 redirect in one step. I want to avoid two redirects as in:

www.<domain>.net -[301]-> <domain>.net -[301]-> <domain>.com
hcristea
  • 93
  • 8

2 Answers2

1

You can use:

RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)\.(?:com|net|org)$ [NC]
RewriteCond %{HTTP_HOST} !^%1\.com$ [NC]
RewriteRule ^ http://%1.com%{REQUEST_URI} [R=301,NE,L]
Croises
  • 18,570
  • 4
  • 30
  • 47
  • Doesn't seem to work. non .com get redirected to .com but .com ends up redirecting to itself. Too many redirects. – hcristea Aug 03 '17 at 15:21
  • Did you clear your cache or try with other browser ? – Croises Aug 03 '17 at 18:08
  • Yes, I tried with multiple browsers, cleared cache and also used curl I have this domain: santestlaborator.ro, santestlaborator.com (I changed the RewriteCond to include .ro) Using `curl -I http://www.santestlaborator.com` I get 301 but the same thing i get for `curl -I http://santestlaborator.com` – hcristea Aug 04 '17 at 10:35
  • The `%1` from the 2nd RewriteCond line doesn't bind to the `(.+)` group from the first RewriteCond. So when `HTTP_HOST` is `.com`, the second RewriteCond is true because `.com` is different than evaluated `.com`. It works when i hard code the domain in the 2nd RewriteCond, instead of `%1` – hcristea Aug 06 '17 at 16:01
0

Starting from the idea posted by Croises, this is what I end up with:

RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)\.(?:net|org)$ [NC,OR]
RewriteCond %{HTTP_HOST} ^www\.(.+)\.(?:com)$ [NC]
RewriteRule ^(.*)$ http://%1.com/$1 [R=301,NE,L]
hcristea
  • 93
  • 8