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; # 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"; } # Otherwise return 200 "Welcome to $"; }

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.

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

server { listen 80; listen 443 ssl; # Listen and * domains # Get $subdomain variable from domain name server_name ~^(?<subdomain>.+)\.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"; } return 200 "Welcome to $"; }

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