nginx location 常见匹配规则

更新日期: 2017-02-18 阅读次数: 12523 分类: Nginx

整理一下 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';
}

实际测试结果

  • 访问 /static/a/a.php 返回 D
  • 访问 /static/a/ 返回 F
  • 访问 /static/ 返回 C
  • 访问 http://localhost 返回 A
  • 访问 http://localhost/ 返回 B
  • 访问 /src/a.php 返回 E

所以,优先级为

  • =
  • ^~ 路径
  • ~,~* 正则路径
  • 起始路径匹配
  • /

参考

关于作者 🌱

我是来自山东烟台的一名开发者,有敢兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式