Apache2 wildcard DNS and dynamic virtual hosts

We can utilize the power (.. or lack?) of mod_rewrite in Apache2 to dynamically add subdomains for all subdirectories in a certain folder. I cannot recall where i first read how to do this, but all creds goes to someone on the Internet! Also, this only works “out-of-the-box” for Debian Lenny running latest stable version of Apache2, but it should work on all systems running Apache2, with slight modification.

First we need to enable some modules:

a2enmod rewrite vhost_alias
/etc/init.d/apache2 restart

Next up we do some rewrite magic, you need to change some paths and domains to reflect your setup, personally I just use some search and replace in nano to reflect whatever domain and site I’m setting up.

<VirtualHost *:80>
ServerName eksempel.no
ServerAlias *.eksempel.no #wildcard catch all
VirtualDocumentRoot /var/www/%1
UseCanonicalName Off
IndexOptions FancyIndexing
### Use mod_rewrite to direct eksempel.no to www.eksempel.no
RewriteEngine On
RewriteCond %{HTTP_HOST} ^eksempel.no
RewriteRule (.*) http://www.%{HTTP_HOST}$1 [R=301,L]
### Logging
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
CustomLog /var/log/apache2/access_log_eksempel combined
<Directory /var/www>
AllowOverride None
</Directory>
</VirtualHost>

You must also restart Apache2 for your changes to apply.

/etc/init.d/apache2 restart

Leave a Reply