Linux and PHP web application support and development (Bromsgrove, UK)

tel: 0845 0046746

Configuring multiple websites with ease using Apache

When using Apache to host websites, developers tend to either have one configuration file with multiple sites defined within in it (often /etc/httpd/httpd.conf or similar), or end up dealing with a swarm of separate files in /etc/apache2/sites-available – one per domain.

If all the domains are identical, in terms of file structure – apart from the hostname – then we can use Apache’s mod_vhost_alias module to simplify the configuration. When combined with mod_rewrite and use of some Apache environment variables (e.g. %{HTTP_HOST}), your configuration can become much more manageable.

So, you can go from multiple virtual hosts configured similar to the below – where all that’s changing between site(s) is effectively the hostname – :

<Virtualhost *:80>
    ServerName mydomain.com
    ServerAlias www.mydomain.com
    DocumentRoot /var/www/vhosts/mydomain.com/public/
    <Location '/'>
         Allow from ALL
         AllowOverRide ALL
    </Location>

    CustomLog /var/log/apache2/mydomain.com-access.log combined
    ErrorLog /var/log/apache2/error.log
</VirtualHost>

To :

<VirtualHost *:80>
    UseCanonicalName Off
    VirtualDocumentRoot /var/www/vhosts/%0/public/
    <Location '/'>
        Allow from ALL
        AllowOverRide ALL
    </Location>
    CustomLog /var/log/apache2/%{HTTP_HOST}-access.log combined
    ErrorLog /var/log/apache2/error.log
</VirtualHost>

Advantages:

  1. Once the directory structure has been created (and DNS configured) sites can be served immediately
  2. No need to restart Apache,
  3. No need to create a new configuration file (one per site etc)

Disadvantages:

  1. Perhaps difficult to handle e.g. www.mydomain.com and mydomain.com being hosted from the same directory (leading to symlinks in e.g. /var/www/vhosts).
  2. Have to rely on .htaccess files for per-site configuration (which may not be desirable ).

Leave a Reply

Your email address will not be published. Required fields are marked *