Skip to content

Instantly share code, notes, and snippets.

@bkozora
Last active January 24, 2019 11:20
Show Gist options
  • Save bkozora/3556841c45fad6f4e225906398ffc5ec to your computer and use it in GitHub Desktop.
Save bkozora/3556841c45fad6f4e225906398ffc5ec to your computer and use it in GitHub Desktop.
Apache - Dynamic Subdomains Using VirtualDocumentRoot
#
# Wildcard VirtualHost Example Using VirtualDocumentRoot
#
# Almost any Apache directive may go into a VirtualHost container.
# This we know from the Apache documentation posted everywhere.
# However, a hidden gem within that documentation is that we can use
# regular expressions to match parts of the requested domain to paths
# on our filesystem by using %1 and other variations.
#
# To use this, all we have to do is create cooresponding directories,
# populate them with web content, and they're automatically served as long
# as the URI we enter matches the regex scheme we have in our vhosts config.
# This all works because of VirtualDocumentRoot /var/www/vhosts/%1/www
#
# /var/www/vhosts/testing/www/index.html -> http://testing.yourdomain.com
# /var/www/vhosts/testing/www/info.php -> http://testing.yourdomain.com/info.php
# /var/www/vhosts/foobar/www/index.html -> http://foobar.yourdomain.com
#
# Worth noting, I ONLY use this on dev environments. The code itself
# is safe, but it opens the door for you being unaware of rogue
# subdomains running under your site by simply creating a directory and
# file in the right (or wrong, depending on outlook) place.
#
<Directory "/var/www/vhosts">
Options Indexes FollowSymLinks ExecCGI
AllowOverride All
Order allow,deny
Allow from all
Require all granted
</Directory>
#
# Wildcard subdomains
#
<VirtualHost *:80>
ServerAlias *.yourdomain.com
VirtualDocumentRoot /var/www/vhosts/%1/www
</VirtualHost>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment