十五年测试老手,长期负责WEB\APP 项目测试,目前主要负责团队管理工作。

Nginx的location匹配规则

上一篇 / 下一篇  2011-12-24 16:21:38 / 个人分类:nginx

文章来源
  • 文章来源:【转载】

Nginx的Location可以有以下几个匹配:51Testing软件测试网)r*ua*K\'VlR
1. =   严格匹配这个查询。如果找到,停止搜索。 
V1wt6\9S B7h02. ^~ 匹配路径的前缀,如果找到,停止搜索。
_4P)fxY)xn&Jm6]$pw03. ~   为区分大小写的正则匹配   
0x hyN`:T04. ~* 为不区分大小写匹配51Testing软件测试网G7L` F+P z

2J#] HizfHTf M/U0例子:51Testing软件测试网Uuu*Gk0@)p

2r"{DJg0t$P Uw0location = / {
U I7{.h%_)K0# matches the query / only.
+z5hW#sUW0# 只匹配 / 查询。
KS8R@3k9M3o1SL0[ configuration A ]
"sh n}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.Nb9Xz p5{;Z0# 匹配任何查询,因为所有请求都已 / 开头。但是正则表达式规则和长的块规则将被优先和查询匹配。51Testing软件测试网 K b m&T\4O`
[ configuration B ]51Testing软件测试网N:Ibt;h
}
4V{c)}OChJ0location ^~ /images/ {51Testing软件测试网 f8g"fr&UzZX^-z Q
# matches any query beginning with /images/ and halts searching,
WpiSq9eN+T0# so regular expressions will not be checked.51Testing软件测试网 _ E]1\ h?
# 匹配任何已 /images/ 开头的任何查询并且停止搜索。任何正则表达式将不会被测试51Testing软件测试网T/cjXns
[ configuration C ]51Testing软件测试网p8usBB&]updr
}51Testing软件测试网+Ar G^ `/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|4e z/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
  1. 使用/ :
    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可以放在/的下面,因为“/是匹配任何查询,但是正则表达式规则和长的块规则将被优先和查询匹配”
  2. 使用~ /* :
    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

  1. Directives with the = prefix that match the query exactly. If found, searching stops.
  2. All remaining directives with conventional strings, longest match first. If this match used the ^~ prefix, searching stops.
  3. Regular expressions, in order of definition in the configuration file.
  4. 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

 

评分:0

我来说两句

Open Toolbar