Domain – What Apache server configuration(s) do I need to map directory name to domain

apache-2.2domainvirtualhost

Say I have a folder ~/apache/ that contains two website directories:
www.website1.com
www.website2.com

Right now I have things set up using the sites-available and sites-enabled configurations which map domains to directories. I'd like to make it so that all I have to do is create a new directory and point the proper domain to my server.

I'll be honest and say I know little to nothing about server configurations. I think I need something along the lines of

VirtualDocumentRoot ~/apache/%0

in a configuration file. httpd.conf? apache2.conf? Or would it be best to put this in a separate config and include it in a main config?

Best Answer

You can potentially completed ditch name-based virtual hosting completely, turn off all your sites-enabled files, and put VirtualDocumentRoot in the main server config.

More likely, what you'll want to do is create a new vhost in sites-available and symlink it to sites-enabled normally, having it act as a catch all. Naming is significant; it needs to be the first file alphabetically in order to be treated as a default.

So:

  • Create an alphabetically-early file that will get loaded first, to be treated as default, such as /etc/apache2/sites-available/0-dynamic.
  • Give the new vhost file some content like this:

    <VirtualHost *:80>
        ServerName catchall
        VirtualDocumentRoot /path/to/domains/%0
        <Directory /path/to/domains>
            Order Allow,Deny
            Allow from all
        </Directory>
    </VirtualHost>
    
  • Enable it: a2ensite 0-dynamic. (if the default is still in place at /etc/apache2/sites-enabled/000-default, rename it so it comes after the new one alphabetically.

This configuration will serve up the dynamically-configured sites from the VirtualDocumentRoot, but can be overridden and served by a different <VirtualHost> when that block has a ServerName or ServerAlias that matches the request. This can be useful if your "blanket" vhost's settings are not appropriate for specific domains.

Edit: (Adding some things I experienced trying to set this up that may be helpful. All credit goes to the original author!)

VirtualDocumentRoot

If you get an error saying

Invalid command 'VirtualDocumentRoot', perhaps misspelled...

check to make sure the vhost_alias module is enabled. If it's not, run

>sudo a2enmod vhost_alias

Handling leading www

Add the following rules (be sure to replace example with your actual domain) to the 0-default file to handle www.example.com and example.com.

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.example.com$ [NC]
RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]

In this example, the www is stripped for all requests, so the directory should be example.com.

Related Topic