一、server_name
server_name的使用方法:
-
之后可以跟多个域名,第一个域名为主域名。
-
泛域名,比如:*.test.com,x.test.*等,只支持*在最前或者最后。
-
正则表达式,前面要加~前缀,例如:server_name www.test.com ~^www\d+\.test\.com$。
-
使用_匹配所有的域名,这个_只是一个占位符,使用其他的!&@等任一字符也行。
-
使用""捕获没有指定hostname的请求,或者是没有在其他server_name中指定hostname的请求。
二、主域名
控制主域名的字段为server_name_in_redirect,默认值为off,上下文为http,server,location。
nginx.conf配置为:
server {
listen 8000;
server_name test-fxt.threatbook-inc.cn localhost;
server_name_in_redirect off;
return 302 /redirect;
.......
}
这里主域名为test-fxt.threatbook.cn,server_name_in_redirect为off。注意这里return了。
使用curl localhost:8000 -I时,返回的信息为:
HTTP/1.1 302 Moved Temporarily
Server: nginx/1.20.1
Date: Tue, 07 Dec 2021 14:56:19 GMT
Content-Type: text/html
Content-Length: 145
Location: http://localhost:8000/redirect
Connection: keep-alive
使用curl test-fxt.threatbook.cn:8000 -I时,返回的信息为:
HTTP/1.1 302 Moved Temporarily
Server: nginx/1.20.1
Date: Tue, 07 Dec 2021 14:56:24 GMT
Content-Type: text/html
Content-Length: 145
Location: http://test-fxt.threatbook-inc.cn:8000/redirect
Connection: keep-alive
也就是说,当server_name_in_redirect为off时,访问的域名是什么,Location中的域名就为什么。
将server_name_in_redirect改为on时,使用curl localhost:8000 -I时,返回的信息为:
HTTP/1.1 302 Moved Temporarily
Server: nginx/1.20.1
Date: Tue, 07 Dec 2021 14:57:17 GMT
Content-Type: text/html
Content-Length: 145
Location: http://test-fxt.threatbook-inc.cn:8000/redirect
Connection: keep-alive
使用curl test-fxt.threatbook.cn:8000 -I时,返回的信息的Location中的域名还是test-fxt.threatbook.cn。
三、获取server_name正则表达式中的变量
获取server_name正则表达式中中的变量的方法有两种:
- 通过变量的索引,比如:server_name ~^(www\.)?(.+).com,这里1为(www\.)匹配到的字段,之后的数字就是该分组位于整个正则中的第几个。
- 通过?,比如
server_name ~^(www\.)?(?<hostName>\.+).com,我们通过$hostName就可以获取到?匹配到的内容。
五、匹配顺序
多个server_name匹配的顺序是:
-
精确匹配,即不包含正则表达式和泛域名的。
-
*在前的泛域名
-
*在后的泛域名
-
当出现多个正则表达式时,按照在nginx.conf文件中出现的顺序匹配。
-
default server,当server_name之后加了default字段时,代表为默认的server_name,比如server_name localhost default。
六、补充
1、Host字段
请求中host字段的作用是标识请求的来源域名,host=hostname + port,那么为什么要标识来源域名呢?
当一个IP对应多个域名,也就是有多个域名可以通过CDN解析到同一个IP上,那么该IP对应的服务器怎么知道请求是来自哪个域名呢?就是使用的Host字段。
2、使用include conf.d/*.conf加载多个配置文件
添加配置:
include mime.types;include vhosts/*.conf;
匹配的顺序是先匹配nginx.conf中的规则,在匹配*.conf文件中的规则。