Apache vhost with and without ‘www’

apache-2.2virtualhost

With Mac OS X 10.6, I'm having some fun moving from the old way of hosting multiple sites (having a block of code in a .conf file for each virtual host) to a slightly less old way (telling the server to look in /sites/ for a folder named example.com and serve whatever is in there.)

Making this happen only requires a couple things: in /etc/apache2/httpd.conf, uncomment this line

#Include /private/etc/apache2/extra/httpd-vhosts.conf

and below that add

VirtualDocumentRoot /sites/%0

Then, in

/etc/apache2/extra/httpd-vhosts.conf

add a block of code that says

<Directory /sites>
 Order Deny,Allow
 Allow from all
</Directory>

My only problem is I can't find an easy way to serve the same content if the visitor requests example.com or www.example.com. With the old way it's easy to make it respond to any subdomain. I'm sure there's a way to do this with the Apache config so I don't have to resort to making lots of symlinks in /sites/. I couldn't find an obvious answer at http://httpd.apache.org/docs/2.0/mod/mod_vhost_alias.html

Ideally, not only would I like to serve the same content with or without the 'www', I'd like to be able to still use subdomains as needed with different, so I'd rather not have everything (*.example.com) serve from the same folder.

Best Answer

You're going to have problems with cookies not crossing over between the sites if you have (effectively) 2 virtual hosts with the same document root. A better solution would be to redirect everything for a non www domain to the corresponding www domain. There are lots of different ways to do this, e.g. using a 404 handler in the (empty) default vhost or using mod_rewrite on %{SERVER_NAME}