dynamic server name and aliases

Francis Daly francis at daoine.org
Sat Feb 20 08:58:25 UTC 2016

On Fri, Feb 19, 2016 at 02:22:35AM -0500, spyfox wrote:

Hi there,

> server {
> 	listen *:80;
> 	server_name ~^i(?<instanceId>\d+)\.domain$;
>         ...

Presumably later in this config, you do something with $instanceId,
and you have a way to handle it not being set.

> It works fine. I have single config to handle all requests for all
> subdomains. 
> I need to allow users specify custom domains as aliases, e.g.:
> i1.domain, super-user.com, another-domain.net -> user #1
> i2.domain, custom.domain -> user #2
> How can I add aliases without copy/paste config for each user?

Use "map" to turn your list of domains into the appropriate
instanceId. Then change your server_name directive not to set that

Something like:

  map $host $instanceId {
    default "";
    ~^i(?P<a>\d+)\.domain$ $a;
    super-user.com 1;
    another-domain.net 1;
    custom.domain 2;

  server {
    listen *:80 default;
    server_name whatever;
    # use $instanceId if it is set

You could also set the default $instanceId to a particular value that
means "not set", and have the rest of the system use that value for an
"unknown" account.

The alternative approach would be to have a separate server{} block
for each account, with lots of duplication that is handled by your
config-generator-from-template system. But f you want a single server{}
block, the above is probably the simplest way.

Good luck with it,

Francis Daly        francis at daoine.org

More information about the nginx mailing list