Apache auto-create Virtual-Hosts*

In this guide we’ll create a generic apache config file to ‘automatically’ create virtual hosts for a specific domain in your server

Sometimes you have a development server with one primary domain, and some sub-domains with your projects and/or stuff that still need to be validated

Firstly you will need to disable SELinux or configure the folders appropriately ( not covered in this guide ).

After having done this step, you can just append to your base apache configuration the following.


UseCanonicalName    Off
#Allowing access to public_html folders
<Directory "/srv/apache/*/public_html/">
    AllowOverride All
    Order allow,deny
    Allow from all
    # Allow open access:
    Require all granted
</Directory>

This configuration enables any folder that have the path ‘/srv/apache/*/public_html/’ to be used as a root folder for a virtual host,
we can then proceed to create the main virtual host.


#Creating the Primary Domain
<VirtualHost *:80>
    ServerAdmin [email protected]
    ServerName example.com
    Options +FollowSymLinks
    DocumentRoot /srv/apache/domain/public_html/
</VirtualHost>


The next step is creating a config file, or appending to the main domain config file, with the following.


#Creating the entry to *.example.com
<VirtualHost *:80>
    ServerAdmin [email protected]
    ServerAlias *.example.com
    Options +FollowSymLinks
    VirtualDocumentRoot /srv/apache/%1/public_html/
</VirtualHost>

If you followed this steps, you can easily spin up new vhosts just creating the folder
‘/srv/apache/vhost/public_html/’ it will be accessible by the link http://vhost.example.com/

Sources:

https://httpd.apache.org/docs/2.4/mod/mod_vhost_alias.html
https://httpd.apache.org/docs/2.4/vhosts/mass.html
https://httpd.apache.org/docs/current/mod/core.html.en
https://httpd.apache.org/docs/current/bind.html
https://httpd.apache.org/docs/current/configuring.html