?? Nginx can respond to wildcard subdomains (via *), great for multi-tenancy.
— Chris Fidao (@fideloper) May 22, 2018
But we can also *capture* a subdomain value!
In the last 2 examples:
1. We pass the subdomain to PHP
2. Config a dynamic the web root
3. Separate log files by subdomainhttps://t.co/JymDb8odH8 pic.twitter.com/yksPa44qWi
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:
- Set a different web root per subdomain
- 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;
}