May 22, 2018

Multi-Tenancy in Nginx

We see how to configure Nginx to respond to wildcard subdomains, great for multi-tenancy!

Nginx can use a wildcard * to serve multiple subdomains. For example, we can have a server configuration respond to any subdomain *.myapp.io.

Variables

However we can also grab the subdomain and set it's value to a variable!

In the second server configuration, we see the subdomain being captured using RegEx. The variable is named $account. We can then use $account in any way we need. It could be set as a header in a proxied HTTP request. In our example, we pass it as an extra FastCGI parameter, so it appears in our PHP $_SERVER global.

That variable can be used anywhere in the server configuration too. In the last example (which may not be best for multi-tenancy apps, but it's up to you) we see it used to:

  1. Set a different web root per subdomain
  2. Change the logfile names per subdomain

The Config

Here's the configuration from the screenshot:

server {
    server_name *.myapp.io;
}

server {
    server_name ~^(?<account>.+)\.myapp\.io$;

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
        fastcgi_param ACCOUNT $account; # $_SERVER['ACCOUNT']
    }
}

server {
    server_name ~^(?<account>.+)\.myapp\.io$;

    root /var/www/$account;

    access_log /var/log/nginx/$account-access.log;
    error_log  /var/log/nginx/$account-error.log;
}

All Topics