Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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) ?

like image 220
mozg Avatar asked Feb 21 '14 05:02

mozg


2 Answers

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]
like image 130
anubhava Avatar answered Nov 02 '22 05:11

anubhava


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] 
like image 22
Hunter Frazier Avatar answered Nov 02 '22 04:11

Hunter Frazier