nginx location 常见匹配规则

发布时间: 2017-02-18 16:46:17 作者: 大象笔记

整理一下 nginx location 的常见规则。

需要注意的是,Nginx Location 规则并不是按照书写顺序进行优先匹配的。 而是按照规则优先级进行匹配。

~* 
case insensitive matching, 不区分大小写的正则匹配
~ 
case sensitive matching, 即区分大小写的正则匹配
= 
exact match, 精确匹配
^~
匹配任何以会面规则开头的地址,匹配以后,不在往下检索正则,立即采用这一条。

实例

location / {
	# 因为所有的地址都以 / 开头,所以这条规则将匹配到所有请求
	# 但是正则和最长字符串会优先匹配
	add_header Content-Type text/plain;
	return 200 'A';
}

location = / {
	# 精确匹配 / 
	add_header Content-Type text/plain;
	return 200 'B';
}

location /static/ {
	# 匹配任何已 /static/ 开头的请求,但是匹配之后,仍然会继续向下检索 
	# 只有当后面的正则匹配没有匹配到时,才会应用到此条规则. 疑问,不使用 ~*, ~, ^~ 的都不是正则匹配么?
	add_header Content-Type text/plain;
	return 200 'C';
}

location ~* (\.php$|\.htaccess$|\.git) {
	# 不区分大小写的正则匹配以 .php 等结尾的请求
	add_header Content-Type text/plain;
	return 200 'D';
}

location ^~ /src/ {
	# 匹配任何以 /src/ 开头的地址,匹配以后,不在往下检索正则,立即采用这一条。
	add_header Content-Type text/plain;
	return 200 'E';
}

location /static/a/ {
	add_header Content-Type text/plain;
	return 200 'F';
}

实际测试结果

所以,优先级为

参考

我是一名山东烟台的开发者,联系作者