-1

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?

JASSY
  • 91
  • 7

1 Answers1

1

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.

pensivepie
  • 106
  • 1
  • 6
  • Many thanks for this. Unfortunately it is not working as expected. under the `/var/www/clients` directory I have a directory `client1` with an index.html. I also have an index.html under the catch-all directory. If I navigate to `http://client1.localhost.com` nginx is returning the catch-all page (i.e. going directly to `$rootdir` instead of `$rootdir/client1`. – JASSY Jun 08 '15 at 10:18
  • I have switched the order of setting the default. It should work now. – pensivepie Jun 08 '15 at 13:20
  • I have changed the `server` block to `server { listen 8080; server_name *.localhost.com; if ( -d "/var/ww/clients/$subdir" ) { set $rootdir "/var/www/clients/$subdir"; } if ( $rootdir == "" ) { set $rootdir '/var/www/clients'; } root $rootdir; } ` but when I try to restart nginx with `sudo service nginx restart` it fails. – JASSY Jun 08 '15 at 13:47
  • Thanks. I went ahead and tested and found the error. I also simplified by taking from your example of what you tried. – pensivepie Jun 08 '15 at 14:08