htaccess redirect all subdomains + www to domain with cname, vhosts and htaccess

11,283

Solution 1

redirect *.domain.com -> domain.com

Just change your rule to this:

RewriteEngine On

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

Solution 2

Set your server alias to *.domain.com in your Apache config, below your server name:

ServerName domain.com
ServerAlias *.domain.com

Everything to non-www:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^(.+)\.domain\.com$   [NC]
RewriteRule ^ http://domain.com/  [L,R]

Everything to www:

RewriteEngine On 
RewriteCond %{HTTP_HOST} ^(.+)\.domain\.com$   [NC] 
RewriteCond %{HTTP_HOST} !^www\. 
RewriteRule ^ http://www.domain.com/  [L,R] 
Share:
11,283
mozg
Author by

mozg

Updated on June 15, 2022

Comments

  • mozg
    mozg almost 2 years

    I have a rather simple problem for someone who knows, I just cant find the answer that I need. I have moved to vps and try to configure vm by myself. I need redirects:

    1. domain.com - default
    2. www.domain.com -> domain.com
    3. *.domain.com -> domain.com

    I`ve already done .htaccess for www -> non-www, so I have:

    RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
    RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
    

    Added A and CNAME:

    • www - @
    • * - @

    Added virtualhost

    • ServerAlias www.domain.com *.domain.com

    Am I doing right (CNAME, vhost, .htaccess) or it can me done simplier?

    Can you please help me redirect *.domain.com -> domain.com (guess in .htaccess) ?