Convert Apache VirtualHost to nginx Server Block for Dynamic Subdomains

I have a web app running on Apache where the virtual hosts file is configured to route requests to subdomains to specific folders. Rather than having to modify the host file every time a subdomain is created, this allows me to dynamically route URLs to the relevant folder (with a catchall if the folder doesn’t exist) –

<VirtualHost *:8080>
    ServerName localhost.com
    ServerAlias *.localhost.com
    VirtualDocumentRoot "/var/www/clients/%1"
    ErrorLog "logserrors.log"
    <directory "/var/www/clients/%1">
        Options Indexes FollowSymLinks
        AllowOverride all
        Order Deny,Allow
        Deny from all
        Allow from all
    </directory>
</VirtualHost>

I am trying to convert the above to nginx but cannot find the right logic to extract the subdomain from the URL and then set the root variable in the config file.

Can anyone help me to write the server {} block for nginx, together with a catch-all block if the root path doesn’t exist?


Source: apache

Leave a Reply