Convert Apache VirtualHost to nginx Server Block for Dynamic Subdomains

543 views Asked by At

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 "logs\errors.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?

1

There are 1 answers

4
pensivepie On BEST ANSWER

Use a named regex capture in the server_name that you can refer to later.

server {
    listen 8080;
    server_name ~^(?<subdir>.*)\.localhost\.com$ ;

    set $rootdir "/var/www/clients";
    if ( -d "/var/www/clients/${subdir}" ) { set $rootdir "/var/www/clients/${subdir}"; }
    root $rootdir;
}

What your are doing is setting your default root directory to a variable $rootdir and then overwriting it if the subdirectory set by $subdir exists.