Dynamic virtual hosts on Apache

Dynamic virtual hosts on Apache

This virtual host configuration will automatically choose a directory for the site's document root based on the domain name.

  1. Set up a virtual host:

    /etc/httpd/conf.d/dynamic.conf

    <VirtualHost _default_:80> RewriteEngine on # Remove "www." from domain names by redirecting. RewriteCond %{HTTP_HOST} ^www\. RewriteRule ^(.*) %{HTTP_HOST}`$1 [C] RewriteRule ^www\.([^\_]*)\`(.*)$ http://$1$2 [R=301,L] # Use components of the domain to determine the document root. # %0 is the whole domain. # %1 is the first part (using dotted delimiters). # %-2 is the second to last part. ServerAlias *.example.com UseCanonicalName Off VirtualDocumentRoot /var/www/html/workspace/%1/htdocs </VirtualHost>
  2. Add this to the .htaccess file configuring the application:

    /var/www/html/workspace/YOUR-APPLICATION/htdocs/.htaccess

    [...] RewriteBase /