Resolving subdomains dynamically via Nginx

2 min read

You can define and use variables in server_name.

Offical nginx docs page.

Example: return message

Lets imagine that you need to return message depended on the subdomain name.

Config file:

server { listen 80; # Define available domains and filling up subdomain variable server_name ~^(?<subdomain>.+)\.domain\.com domain.com; # Set up content-type header add_header Content-Type text/plain; # Is subdomain is empty then show message without subdomain if ($subdomain = "") { return 200 "Welcome to domain.com"; } # Otherwise return 200 "Welcome to $subdomain.domain.com"; }

Here is a result for my test domain:

Example: define root

Subdomains sites with a same configurations can be processed by redefining root param:

server { listen 80; ## Save subdomain to variable server_name ~^(?<subdomain>.+)\.domain\.com$; ## Check for a subdomain's directory existing if (!-d "/var/www/$subdomain") { return 404; } ## Define root directory by the subdomain root /var/www/$subdomain; # ... all other nginx params }

Enable SSL certificate

You can request and use a wildcard SSL-certificate for subdomains.

codex.so

For example I just got a certificate for domain abc.taly.space and subdomains *.abc.taly.space without any troubles. Then I create an example config for server.

server { listen 80; listen 443 ssl; # Listen abc.taly.space and *.abc.taly.space domains # Get $subdomain variable from domain name server_name ~^(?<subdomain>.+)\.abc\.taly\.space abc.taly.space; # Include ssl configs and cert's params include snippets/certs/abc_taly; # Return data as a plain text add_header Content-Type text/plain; if ($subdomain = "") { return 200 "Welcome to abc.taly.space"; } return 200 "Welcome to $subdomain.abc.taly.space"; }

Then you can open sites by domain or with a subdomain.