DavidB DavidB - 1 year ago 115
Apache Configuration Question

htaccess Rewrite URL based on TLD

On my website, I am interested in moving my forums from a subdirectory to a subdomain. The forums are currently located at

, and I want to move them to
. After the move, I want to use htaccess to 301 redirect all forum traffic to the subdomain, but the problem is that I have two TLDs for my site, a
domain and a

I am currently trying to redirect traffic using this:

RewriteCond %{HTTP_HOST} !=forums.example.net
RewriteRule ^forums(/(.*))?$ https://forums.example.net/$2 [L,R=301]

RewriteCond %{HTTP_HOST} !=forums.example.com
RewriteRule ^forums(/(.*))?$ https://forums.example.com/$2 [L,R=301]

This only half-works. Regardless of which TLD I visit, it always redirects me to
, even if I am visiting from
, in which case I want it to go to
. How could I achieve this?

Answer Source

You can use this singe rule as very first rule in forums/.htaccess instead of top level .htaccess:

RewriteEngine On

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

For root .htaccess use this rule as your first rule:

RewriteEngine On

RewriteCond %{HTTP_HOST} ^(?:www\.)?(example\.(?:com|net))$ [NC]
RewriteRule ^forums(/.*)?$ http://forums.%1/$1 [NC,L,R=301,NE]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download