Search code examples
regexapache.htaccesslamp

Redirect all subdomains to a new domain with htaccess


I am trying to redirect all subdomains to a new domain with htaccess.

  1. All subdomains with any path get forwarded:

    y.domain.com/anything --> y.domain2.com/anything

  2. Don't forward the main domain or www:

    domain.com --> domain.com

    www.domain.com --> www.domain.com

I have tried the following but does not seem to be working:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^(.+)\.domain\.com$ [NC]
RewriteCond %{HTTP_HOST} !www.domain.com$ [NC]
RewriteRule ^(.*)$ http://%1.domain2.com/ [L,R=301]

Solution

  • You may use this rule:

    RewriteEngine on
    
    RewriteCond %{HTTP_HOST} ^(?!www\.)(.+)\.domain\.com$ [NC]
    RewriteRule ^ http://%1.domain2.com%{REQUEST_URI} [L,R=301,NE]
    

    Make sure to use a new browser to test this change or completely clear browser cache.