3

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.

Oliver Joseph Ash
  • 361
  • 3
  • 5
  • 14

2 Answers2

6

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>
Shane Madden
  • 114,520
  • 13
  • 181
  • 251
1

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.

mr.spuratic
  • 3,430
  • 20
  • 14