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

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, hello.domain.com 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 helloworld.domain.com 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

2 Answers 2

up vote 6 down vote accepted

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

NameVirtualHost *:80
<VirtualHost *:80>
  ServerName catchall.domain.com
  ServerAlias *.domain.com
  VirtualDocumentRoot /var/www/%1
</VirtualHost>
<VirtualHost *:80>
  ServerName helloworld.domain.com
  DocumentRoot /var/www/helloworld/public
</VirtualHost>
share|improve this answer
    
Thanks. Why ServerName catchall.domain.com? Why not just have ServerAlias *.domain.com? –  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 *.domain.com? –  Oliver Joseph Ash Jan 11 '13 at 18:45
1  
@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 http://httpd.apache.org/docs/2.2/vhosts/mass.html for many of the mass-virtual-hosting tips.

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.