Eli Ivanova
Eli Ivanova

Reputation: 83

.htaccess redirect subdomains with subfolder to root, exclude subdomains themself

I'm sorry if this was asked before but I couldn't get an answer.

I would like to 301 redirect subdomains with subfolder to root, but to ignore subdomains:

test.example.com -> test.example.com
test.example.com/folder1/folder2 -> example.com/folder1/folder2
anyother.example.com -> anyother.example.com
anyother.example.com/folder1/folder2 -> example.com/folder1/folder2

Thanks.

Upvotes: 1

Views: 109

Answers (1)

anubhava
anubhava

Reputation: 784918

Put this code in your DOCUMENT_ROOT/.htaccess file:

RewriteEngine On

RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTP_HOST} ^[^.]+\.(example\.com)$ [NC]
RewriteRule ^(.+)$ http://%1/$1 [L,NE,R=301]
  1. RewriteCond %{HTTP_HOST} !^www\. makes sure rule doesn't fire for www.example.com
  2. RewriteCond %{HTTP_HOST} ^[^.]+\.(example\.com)$ to make sure we use it for sub domain
  3. ^(.+)$ in RewriteRule to make sure we don't redirect landing page of sub domains.

Upvotes: 1

Related Questions