Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

In my apache setup I would like to have number of directories named after domain names that will be served based on subdomain hierarchy.

For example, given existent two directories:


Apache will serve following directories based on request host:

  1. ->
  2. ->
  3. ->
  4. ->

mod_vhost_alias can't test existence of directories or manipulate request host as far as I know. Therefore it is not suitable for the task.

I was however successful with following mod_rewrite implementation:

<VirtualHost *:80>
    # Omitting this line produces strange behaviour, requesting the
    # server will try to look up /var/www/test.localhost/var/www/test.localhost
    # Clarification on this issue is very welcome
    DocumentRoot /var/www

    RewriteEngine on

    # Full domain
    RewriteCond %{HTTP_HOST} ^(.*)$
    RewriteCond /var/www/%1 -d
    RewriteRule (.*) /var/www/%1/$1 [L]

    # -1 domain level
    RewriteCond %{HTTP_HOST} ^.+?\.(.*)$
    RewriteCond /var/www/%1 -d
    RewriteRule (.*) /var/www/%1/$1 [L]

I would like to know if there is a better solution for this task and if my implementation has any pitfalls.

So far I only discovered that I need to specify "RewriteBase /" for scripts that rely on rewrite and supposed to be put on top level.

This is not intended for production and performance impact is neglectable.

share|improve this question
up vote 0 down vote accepted

I'd say it's quite a clever way to do it. The obvious pitfall is that it's not going to work for your fourth example - you only strip off the first subdomain part, so will be translated to instead of

You could use an external program, such as a perl script, to do the rewriting, to catch more specialized cases, by using the RewriteMap directive. That'll bring in even more complications and decrease performance even more.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.