Resolving subdomains dynamically via Nginx

1 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 }