Domain and subdomain wildcards on Apache as dynamic subfolders Domain and subdomain wildcards on Apache as dynamic subfolders apache apache

Domain and subdomain wildcards on Apache as dynamic subfolders


For dynamic domain name configuration based on the names of folders you create in
/public_html/sites/, you can use the ServerAlias and VirtualDocumentRoot directives.

Add something like this in your apache virtualhost configuration file:

<VirtualHost *:80>    ...    ServerAlias *    VirtualDocumentRoot /public_html/sites/%0    ...</VirtualHost>

To understand why %0 is used, consider the domain m.rate.movies.net split into parts

Index:             %1      %2      %3       %4Domain:             m     rate    movies    netNegative Index:    %-4     %-3     %-2      %-1

The one I chose to use, %0 represents the entire domain name - m.rate.movies.net. This allows you to support domain names that can have varying number of parts separated by dots. This makes sub-directories created inside /public_html/sites/ be the document root for any domain name pointed to your server's IP.

  /public_html/sites/domain.com        --> http://domain.com/  /public_html/sites/blog.writers.org  --> http://blog.writers.org/  /public_html/sites/m.rate.movies.net --> http://m.rate.movies.net/

If you used something like VirtualDocumentRoot /public_html/sites/%1

You will have to create the sub-directories this way

  /public_html/sites/domain   --> http://domain.com/  /public_html/sites/blog     --> http://blog.writers.org/  /public_html/sites/m        --> http://m.rate.movies.net/

You can also use a combination: VirtualDocumentRoot /public_html/sites/%-2\.%-1

  /public_html/sites/domain.com   --> http://domain.com/  /public_html/sites/writers.org  --> http://blog.writers.org/  /public_html/sites/movies.net   --> http://m.rate.movies.net/

Yet another way: VirtualDocumentRoot /public_html/sites/%-1/%-2/

  /public_html/sites/com/domain   --> http://domain.com/  /public_html/sites/org/writers  --> http://blog.writers.org/  /public_html/sites/net/movies   --> http://m.rate.movies.net/

With these setup, you won't have to edit the virtual host configuration every time you add a new domain. You won't be able to use separate log files for each domain, but for that, you can use a custom log format that includes the host name.