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:
- company.com
- shop.company.com
Apache will serve following directories based on request host:
- www.company.com -> company.com
- us.company.com -> company.com
- shop.company.com -> shop.company.com
- 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.