nginx server_name configuration

Reprinted from: http://onlyzq.blog.51cto.com/1228/535279

 

The server_name directive in Nginx is mainly used to configure name-based virtual hosts. The matching order of the server_name directive after receiving the request is as follows:

1. Exact server_name match, for example:

 

server {
     listen       80;
     server_name  domain.com  www.domain.com;
     ...
}

 

 

2. Strings starting with * wildcards:

server {
     listen       80;
     server_name  *.domain.com;
... }

3. A string ending with a * wildcard:

server {
     listen       80;
     server_name  www.*;
     ...
}

4. Match the regular expression:

server {
     listen       80;
     server_name  ~^(?.+)\.domain\.com$;
... }
nginx will match the server name in the order of 1, 2, 3, 4, and the search will stop after only one match, so we must distinguish its matching order when using this instruction (similar to the location instruction) .
A very useful function of the server_name directive is that it can use the capture function of regular expressions, which can simplify the configuration file as much as possible. After all, the daily maintenance of the configuration file that is too long is also very inconvenient. Here are 2 specific applications:
1. Configure multiple sites in a server block:
server
   {
     listen       80;
     server_name  ~^(www\.)?(.+)$;
     index index.php index.html;
     root  /data/wwwsite/$2;
   }

A site's home directory should have a structure similar to this:

/data/wwwsite/domain.com
/data/wwwsite/nginx.org
/data/wwwsite/baidu.com
/data/wwwsite/google.com

 

This allows the configuration of multiple sites to be done using only one server block.

2. Configure multiple secondary domain names for a site in a server block.

In the actual website directory structure, we usually create a separate directory for the second-level domain name of the site. Similarly, we can use regular capture to configure multiple second-level domain names in a server block:

 

server
   {
     listen       80;
     server_name  ~^(.+)?\.domain\.com$;
index index.html; if ($host = domain.com){
rewrite ^ http://www.domain.com permanent;
} root /data/wwwsite/domain.com/$1/;
}

The directory structure of the site should be as follows:

/data/wwwsite/domain.com/www/
/data/wwwsite/domain
.com/nginx/

In this way, when accessing www.domain.com, the root directory is /data/wwwsite/domain.com/www/, when nginx.domain.com is /data/wwwsite/domain.com/nginx/, and so on.

The function of the following if statement is to redirect the orientation of domain.com to www.domain.com, which not only solves the access to the main directory of the website, but also increases the domain name authority of www.domain.com in seo.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326312404&siteId=291194637