Search code examples
.htaccess

Subdomain alias with htaccess


I have this code for managing a subdomain alias: browsing sub.domain.com it shows domain.com/fp/sub.

RewriteCond %{HTTP_HOST} ^sub\.domain\.com$
RewriteRule (.*) /fp/sub/$1

I have a lot of these subdomain to setup. Is there a way to automate this process placing some variables instead of the correct subdomain/folder name?

I tried this code with no success

RewriteCond %{HTTP_HOST} ^(sub1|sub2)\.domain\.com$
RewriteRule (.*) /fp/$1/$2

Solution

  • Francesco, first correcting your example, the rule should be:

    RewriteRule ^(.*) fp/%1/$1         [L]
    

    The % variables are set in the last successful cond regexp match.

    Second there are lots of options if you have access to the system or vhost config, such as using Rewrite Maps or mass virtual hosts. If you don't have such access are limited to .htaccess, then you need to use one or more rules much as you are already doing. One variant is to use an existence check of the target directory, such as:

    RewriteCond %{HTTP_HOST}            ^(\w+)\.domain\.com$
    RewriteCond %{DOCUMENT_ROOT}/fp/%1 -d
    RewriteRule (.*)                   fp/%1/$1            [L]
    

    Beware that if you are using a shared hosting service, that DOCUMENT_ROOT may not be properly set at rewrite execution, in which case your SHS provider will set up an environment variable to do the same, e.g. %{ENV:DOCUMENT_ROOT_REAL}. Do a phpinfo to find out. See Tips for debugging .htaccess rewrite rules for more advice on how to debug this.