Last Updated: February 25, 2016
·
890
· vimishor

Apache wildcard vhosts

More dynamic than wildcard, but useful, at least for me.

In httpd.conf:

NameVirtualHost *:80
UseCanonicalName Off
<VirtualHost *:80>
    ServerAlias *.dev.box
    DocumentRoot "D:/www/_domains"
    VirtualDocumentRoot "D:/www/_domains/%-3+"
    php_admin_value auto_prepend_file "D:/www/_domains/set_docroot.php"
</VirtualHost>

Now if I create a directory named "example.com" in "D:/www/_domains" I can access it from web browser at http://example.com.dev.box .

Everything works well, except "DOCUMENT_ROOT" which will always point to "D:/www/_domains". To solve this, I created a file "D:/www/domains/setdocroot.php", with
the following content:

<?php
// Append the current directory name to document root

$location = explode(".",$_SERVER['HTTP_HOST']);

# remove `dev.box` suffix
$location = array_slice($location, 0, count($location)-2);

# set new documment root
$_SERVER['DOCUMENT_ROOT'] .= '/'.implode('.', $location);

This will set the corect "DOCUMENT_ROOT" for each domain.

Happy coding !