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

Currently I have several virtual hosts set up for individual subdomains. It would be a lot easier if I could tell Apache to automatically find the folder using a wildcard. For example, would use the /var/www/hello directory as its DocumentRoot.

I would like to be able to define exceptions however, such as if I wanted to point to /var/www/helloworld/public instead.

I've looked around but all of the examples seem to be doing something different.

share|improve this question
up vote 6 down vote accepted

You'll be able to configure that behavior with something along these lines:

NameVirtualHost *:80
<VirtualHost *:80>
  ServerAlias *
  VirtualDocumentRoot /var/www/%1
<VirtualHost *:80>
  DocumentRoot /var/www/helloworld/public
share|improve this answer
Thanks. Why ServerName Why not just have ServerAlias * – Oliver Joseph Ash Jan 11 '13 at 17:58
@OliverJosephAsh You need a ServerName in that vhost, but its name really doesn't matter - ServerName a would work just as well. – Shane Madden Jan 11 '13 at 18:12
Could I just do ServerName * – Oliver Joseph Ash Jan 11 '13 at 18:45
@OliverJosephAsh No, the wildcard must be in ServerAlias. – Shane Madden Jan 11 '13 at 18:50

The above uses mod_vhost_alias, I use mod_rewrite, something like this in the first defined (default) VirtualHost:

RewriteEngine on
RewriteMap lc int:tolower

RewriteCond /var/www/${lc:%{SERVER_NAME}} -f 
RewriteRule ^/(.*)   /var/www/${lc:%{SERVER_NAME}}/htdocs/$1  

This lets you add a little more logic, should it be useful. I had thought that another advantage of the mod_rewrite approach is that it would handle any domain, not necessarily sub-domains -- but on testing (httpd-2.2.x) it seems that ServerAlias will accept any reasonable * and ? wildcards, including *.com or even *. So, no win if you don't need the complexity.

In either case, it can be useful to use LogFormat/CustomLog directives to put the requested virtualhost name (%v) into the logs:

LogFormat   "%v %h %l %u %t \"%r\" %>s %b"   log-with-vhost

See also for many of the mass-virtual-hosting tips.

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.