十五年测试老手,长期负责WEB\APP 项目测试,目前主要负责团队管理工作。
Nginx的location匹配规则
上一篇 /
下一篇 2011-12-24 16:21:38
/ 个人分类:nginx
Nginx的Location可以有以下几个匹配:51Testing软件测试网)r*ua*K\'VlR
1. = 严格匹配这个查询。如果找到,停止搜索。
V1wt6\9S
B7h02. ^~ 匹配路径的前缀,如果找到,停止搜索。
_4P)fxY)x n&Jm6]$pw03. ~ 为区分大小写的正则匹配
0xhyN`:T04. ~* 为不区分大小写匹配51Testing软件测试网G7L`F+P
z
2J#]
HizfHTfM/U0例子:51Testing软件测试网Uu u*Gk0@)p
2r"{D Jg0t$P Uw0location = / {
UI7{.h%_)K0# matches the query / only.
+z5hW#sUW0# 只匹配 / 查询。
KS8R@3k9M3o1SL0[ configuration A ]
"shn}f
Z&A9B)q%^0}51Testing软件测试网t/D-F {'DR@w/R
location / {
(LZ~3eL c
F+u0# matches any query, since all queries begin with /, but regular
4\XVGl(JI(a0# expressions and any longer conventional blocks will be51Testing软件测试网1C2Uju]bZ
# matched first.
5qa$K0^6O.Nb9Xzp5{;Z0# 匹配任何查询,因为所有请求都已 / 开头。但是正则表达式规则和长的块规则将被优先和查询匹配。51Testing软件测试网Kb
m&T\4O`
[ configuration B ]51Testing软件测试网N:Ibt;h
}
4V{ c)}OChJ0location ^~ /images/ {51Testing软件测试网
f8g"fr&UzZX^-zQ
# matches any query beginning with /images/ and halts searching,
WpiSq9e N+T0# so regular expressions will not be checked.51Testing软件测试网
_E]1\h?
# 匹配任何已 /images/ 开头的任何查询并且停止搜索。任何正则表达式将不会被测试。51Testing软件测试网T/cjXns
[ configuration C ]51Testing软件测试网p8usB B&]updr
}51Testing软件测试网+ArG^ `/c\K
location ~* ".(gif|jpg|jpeg)$ {51Testing软件测试网$T&E0C/L1Yd3En5`
# matches any request ending in gif, jpg, or jpeg. However, all
+Ht.ZfFE0# requests to the /images/ directory will be handled by51Testing软件测试网XqFL2VLsR
f
# Configuration C.
)a3I6|4ez/I0U0# 匹配任何已 gif、jpg 或 jpeg 结尾的请求。然而所有 /images/ 目录的请求将使用 Configuration C。
z^?0QGm+n0[ configuration D ]51Testing软件测试网2i2a
Q S+y$_
}51Testing软件测试网6CKDY~
如果要定义多个location,则可以有2种方式:
R;@X#I|b0- 使用/ :
location / { client_max_body_size 200m; proxy_connect_timeout 30; proxy_set_header Host $http_host; proxy_set_header x-forwarded-for $remote_addr; proxy_pass http://127.0.0.1:8008; } location /tmp/{ root /; internal; }
采用这种方式,/tmp可以放在/的下面,因为“/是匹配任何查询,但是正则表达式规则和长的块规则将被优先和查询匹配” - 使用~ /* :
location ~ /tmp/ { root /tmp; internal; } location ~ /* { client_max_body_size 20m; proxy_connect_timeout 30; fastcgi_pass fpass; include fastcgi_params; }
采用这种方式,/tmp则必须放在~ /*这个前面,因为~是正则匹配的,正则匹配是有顺序的,只要匹配上就不会再往下匹配了。除非在conf中有定义=或者^~,也就是说=和^~的优先级最高,如果匹配上,就不会再去匹配其它的规则了。
总之,引用Nginx的官方文档的匹配规则:51Testing软件测试网K9c$of)@POg2y
+XEU}rX}0引用
51Testing软件测试网e*O$b&Md
- Directives with the = prefix that match the query exactly. If found, searching stops.
- All remaining directives with conventional strings, longest match first. If this match used the ^~ prefix, searching stops.
- Regular expressions, in order of definition in the configuration file.
- If #3 yielded a match, that result is used. Else the match from #2 is used.
注意:正则表达式的匹配是有顺序的,按顺序匹配。其它的匹配理论上讲是只有优先级,而没有顺序的。51Testing软件测试网,dw,V%\&ls
S
收藏
举报
TAG:
nginx
Nginx
NGINX