Search code examples
.htaccesshttp-redirectsubdomain

Redirect all subdomains except www to main domain


I want to redirect all subdomains except www to https://www.example.com in .htaccess, how can I do this? All subdomains can be accessed.

I only want to redirect the subdomains, not inner pages on the main domain.

Examples: (Should redirect)

  • hello.domain.com
  • test.example.domain.com
  • www.hello.sub.domain.com

Examples of where not to redirect:

  • www.domain.com/hello-world
  • www.domain.com

Current .htaccess file:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www.domain.dk$
RewriteRule ^(.*) https://www.domain.dk/$1 [QSA,L,R=301]

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

Solution

  • This should get you started. Anything apart from www.mydomain.com will be redirected to www.example.com.

    RewriteCond %{HTTP_HOST} !^www.mydomain.com$
    RewriteRule ^(.*) https://www.example.com/$1 [QSA,L,R=301]
    

    Edit:

    Remember that it's the .htaccess in your subdomain folder, or _wildcard_domain.com that you will have to create or edit for this to work.