Search code examples
apache.htaccesshttp-redirectsubdomaincatch-all

How can I correctly catch-all subdomains (and redirect) with .htaccess?


I have wild card subdomains (*.domain.com) set up on my server. I now would like to use .htaccess to redirect all *.domain.com requests to a script main.php on my server. I searched for code that would help accomplish the redirect but I have not been entirely successful. The best working code I have found is:

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

However, www.subdomain.domain.com is redirected to domain.com/www.subdomain instead of domain.com/subdomain. How can this be fixed in the code? Is there a better way of doing this?

Thanks in advance!


Solution

  • Can you try this rewrite rule:

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