Kyle Ross
Kyle Ross

Reputation: 2160

Redirect Multiple Subdomains to another domain name

Got a question about using mod_rewrite to redirect specific subdomains to use another domain. I am looking for the shortest possible way to do this without the need to create a separate rewrite rule for each of my domain names. I will be adding many new domain names (roughly 20-30 domains total).

So let's say my main domain name is example.com and I want to use that domain name for everything. So if any of my other domains are used, they will automatically be redirected to the main domain, preserving the subdomain prefix and the URL path.

Example:
test.example.org => test.example.com
test2.example.co.uk => test2.example.com
test3.example.net/hello/world.php => test3.example.com/hello/world.php

RewriteEngine on
RewriteCond %{HTTP_HOST} ^(.*)\.([a-zA-Z]+)\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1\.example.com/$1 [R=301,L]

I am unsure if the above will work correctly or if it is proper syntax. But basically, I would like to have it match the subdomain prefix, then any domain name, and any TLD (.org, .info, .biz, .co.uk, .net, etc.). I would assume it would need to make sure that it is not the correct main domain (example.com) first to prevent a infinite redirect loop.

Also, is there a possibility to check if HTTPS is ON or OFF and set the redirect correctly? If not, I can always have HTTPS set to ON.

Sorry for this confusion, although I want to make sure I get this right the first time without needing to program each and every one of the domains into the .htaccess.

Thanks! :)

Upvotes: 1

Views: 1122

Answers (2)

TerryE
TerryE

Reputation: 10888

(.*) is greedy so you don't want to use that, and I assume that you don't want to recreate an infinite loop.

RewriteEngine on

RewriteCond   %{HTTPS}s    ^..(s?)
RewriteRule   ^            -                                [E=PROTO:http%1]              

RewriteCond   %{HTTP_HOST} !^\w+\.example\.com$             [NC]
RewriteCond   %{HTTP_HOST} ^(\w+)\.\w+\..+                  [NC]
RewriteRule   ^/?(.*)      %{ENV:PROTO}://%1.example.com/$1 [R=301,L]

Upvotes: 2

Jon Lin
Jon Lin

Reputation: 143886

That rule will not work because it will redirect any host ending with example.com back to example.com and you'll get a redirect loop. You need to change the regex to look like this, to match anything that doesn't end with .com:

RewriteCond %{HTTP_HOST} ^([^\.]+)\.?([a-zA-Z]+)\.(?:(?!com).)*$ [NC]

Upvotes: 1

Related Questions