Dynamic server name and aliases

Hi everybody,
I manage server, where each user has own subdomain:
i1.domain → user #1
i2.domain → user #2
etc

I have a nginx config to handle user’s subdomains:

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

}

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?

Posted at Nginx Forum:

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

Hi there,

server {
listen *:80;
server_name ~^i(?\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
variable.

Something like:

map $host $instanceId {
hostnames;
default “”;
~^i(?P\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,

f

Francis D. [email protected]