Apache VirtualDocumentRoot for wildcard virtualhosts

<VirtualHost *:80>
    UseCanonicalName Off
    VirtualDocumentRoot /mnt/projects/%1/public
    ServerName subdomains.starfall.local
    ServerAlias *.starfall.local

<Directory /mnt/projects/*/public>
    Options Indexes FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all

Now you might run into infinite redirect issue if use together with mod_rewrite. Add this line in the mod_rewrite .htaccess file for each folder under /mnt/projects to stop this.

RewriteBase /

The similar effect can be achieved via mod_rewrite. Put this into /etc/apache2/httpd.conf, or apache2.conf but it needs to be loaded first before virtualhost/conf.d. The point here is to let virtualhost config to override this wildcard.

<VirtualHost *:80>
    UseCanonicalName Off
    RewriteEngine On
    RewriteCond %{REQUEST_URI} !^/icons/
    RewriteCond %{HTTP_HOST} ^(.*)\.starfall.local$
    RewriteRule ^/(.*)$ /mnt/projects/%1/public/$1

You may still need to add “RewriteBase /” in case of infinite redirect.

From what I tested this new method handles:
– allow wildcard request to point to /mnt/projects/SUBDOMAIN_NAME/public
– it doesn’t not interfere with subsequent rewrite rule usually present in .htaccess

1 thought on “Apache VirtualDocumentRoot for wildcard virtualhosts”

  1. Thanks! I’m using your Rewrite solution without any change in .htaccess files. :)
    You can add a Directory confirugation like this:

Leave a Reply