apache.htaccessvhostsreverse-dnsmod-vhost-alias

Apache: Dynamically set Documentroot inside Virtualhost Section based on reverse-DNS Notation


we want to setup one apache-server via VHosts to do the following: We want to route each of our mutliple domains to their corresponding location based on the domain-name (including subdomains, so the amount of Levels may vary) and their reverse-domain-name-notation (reverse-DNS) as directory-name.

For example we want to route admin.example.com to /domains/com.example.admin/public and myshop.net to /domains/net.myshop/public.

We know that to achieve this without reverse-DNS the Config should look like this (based on this post and the mod_vhost_alias documentation):

<VirtualHost *:80>
    UseCanonicalName Off
    VirtualDocumentRoot "/domains/%0/public"
</VirtualHost>

The documentation only talks about rearraging single letters in the domain-name-parts.

We could think of a solution like this:

<VirtualHost *:80>
    UseCanonicalName Off
    VirtualDocumentRoot "/domains/%-1.0.%-2.0.%-3.0.%-4.0.%-5.0.%-5.0.%-6.0/public"
</VirtualHost>

But we could imagine that when there are less (or unlikely more) domain-name-parts it would not work or accumulate leading/trailing dots or something else.

So is it possible and if so how do we achieve this?


Solution

  • I had the same problem and I think there is no way to just reverse order of the parts in domain name. But I end up using this ugly solution. Just have multiple VirtualHost definitions, each wildcarding domains of different depth.

    #For domains 5 levels deep like 'test1.project.dev.mydomain.com'
    <VirtualHost *:80>
      ServerAlias *.*.*.*.com
      VirtualDocumentRoot /webroot/%-1.0.%-2.0.%-3.0.%-4.0.%-5.0/
    </VirtualHost>
    
    #For domains 4 levels deep like 'project.dev.mydomain.com'
    <VirtualHost *:80>
      ServerAlias *.*.*.com
      VirtualDocumentRoot /webroot/%-1.0.%-2.0.%-3.0.%-4.0/
    </VirtualHost>
    
    #For domains 3 levels deep like 'www.mydomain.com'
    <VirtualHost *:80>
      ServerAlias *.*.com
     VirtualDocumentRoot /webroot/%-1.0.%-2.0.%-3.0/
    </VirtualHost>