nginx配置:server_name的作用

作用

案例

修改nginx.conf

server {
	listen 80;
	server_name www;
	location / {
		default_type text/html;
		content_by_lua 
			ngx.say("<p>first</p>")
		;
	}
}

server {
	listen  80;
	server_name www.zkh.com;
	location / {
		default_type text/html;
		content_by_lua 
			ngx.say("<p>second</p>")
		;        
	}
}

server {
	listen 80;
	server_name www.zkh.*;
	location / {
		default_type text/html;
		content_by_lua 
			ngx.say("<p>third</p>")
		;

	}
}

server {
	listen 80;
	server_name ~w+.com;
	location / {
		default_type text/html;
		content_by_lua 
			ngx.say("<p>forth</p>")
		;        
	}
}

server {
	listen 80;
	server_name ~.*zkh.com;
	location / {
		default_type text/html;
		content_by_lua 
			ngx.say("<p>fifth</p>")
		;
	}
}

修改hosts文件

118.126.100.138 www.zkh.com
118.126.100.138 www.zkh.org
118.126.100.138 zkh.com
118.126.100.138 zkh.org

通过jmeter查看请求头,发现请求头携带了Host,由此可知nginx必定会拿它做uri匹配工作

匹配顺序

server_name与host匹配优先级如下:

1、完全匹配

2、通配符在前的,如*.test.com

3、在后的,如

4、正则匹配,如~^.www.test.com$

如果都不匹配

1、优先选择listen配置项后有default或default_server的

2、找到匹配listen端口的第一个server块

参考:1.

2.

经验分享 程序员 微信小程序 职场和发展