Htaccess Rewrite TLD Based URL

On my website, I am interested in moving my forums from a subdirectory to a subdomain. The forums are currently located in example.com/forums, and I want to move them to forums.example.com. After moving, I want to use htaccess for 301 to redirect all forum traffic to a subdomain, but the problem is that I have two TLDs for my site, domain .comand domain .net.

I'm 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 is only half the job. No matter which TLD I visit, it always redirects me to forums.example.net, even if I visit from example.com/forums, in which case I want it to go to forums.example.com. How could I achieve this?

+4
source share
2 answers

You can use this singe rule as the first rule in instead of the top level .htaccess: forums/.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]
+2
source

Please use the rules below so that the correct redirection works the way you want it.

Rewritengine On
RewriteCond %{HTTP_HOST} ^example\.com$
RewriteRule ^forums$ http://forums.example.com/? [L,R=301]
RewriteCond %{HTTP_HOST} ^example\.net$
RewriteRule ^forums$ http://forums.example.net/? [L,R=301]
+1
source

Source: https://habr.com/ru/post/1651225/


All Articles