Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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:

  1. company.com
  2. shop.company.com

Apache will serve following directories based on request host:

  1. www.company.com -> company.com
  2. us.company.com -> company.com
  3. shop.company.com -> shop.company.com
  4. foo.bar.shop.company.com -> shop.company.com

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 company.com 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]
</VirtualHost>

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

1 Answer 1

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 foo.bar.shop.company.com will be translated to bar.shop.company.com instead of shop.company.com

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

 
discard

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.