Configure Nginx subdomain generic resolution binding to a separate directory

  

Simple record:

Requirements description

The web server is Nginx and you want to configure generic subdomain resolution. In fact, with a little modification, configuring pan-domain name resolution is not difficult.

Resolution and Analysis

Make the following configuration (instruction) in the Nginx configuration file:


server { server_name domain.com www.domain. Com *.domain.com ; set $subdomain ''; if ($host ~* (\\b(?!www\\b).+)\\.domain.com) { set $subdomain -$1; } root /home/User/www$subdomain/; }

Explanation:

First, use the wildcard * when defining server_name to allow Nginx to accept access to any subdomain.

Then, analyze $host and find the name of the subdomain. This regular expression is copied online, in order to match the subdomain name, not the access at the beginning of www and the access without www. The previous set is because Nginx's If does not have Else, so the $subdomain is first empty by default. Finally, when defining root, use the $subdomain variable.

Copyright © Windows knowledge All Rights Reserved