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

Nginx的location匹配规则

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

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

Nginx的Location可以有以下几个匹配:51Testing软件测试网\Sq ^Q%H)v
1. =   严格匹配这个查询。如果找到,停止搜索。 
Q,Z!QoBID3@02. ^~ 匹配路径的前缀,如果找到,停止搜索。51Testing软件测试网8M0l1h"Z2S-W
3. ~   为区分大小写的正则匹配   
H5t;K9z/}3__m#K04. ~* 为不区分大小写匹配
D _cF YTWT1]L*W0
q|r%G/H%Et0例子:
&O*K6H TS_IQ051Testing软件测试网.Xw `+@J5J
location = / {
(nC6X"r P/_R0# matches the query / only.51Testing软件测试网@1o`#l,K"iMV'G
# 只匹配 / 查询。
8N9aI&\3@ga9a0[ configuration A ]
?+LM"c'n}7g4~A#r0}
\-W.i Ti.{#J}0location / {51Testing软件测试网"Uq"Yz,U%bn2t
# matches any query, since all queries begin with /, but regular51Testing软件测试网7G;X$sQ"@$U
# expressions and any longer conventional blocks will be
1hG(Y q'T(b3ma0# matched first.
I `6nX I]&P [0# 匹配任何查询,因为所有请求都已 / 开头。但是正则表达式规则和长的块规则将被优先和查询匹配。
6y Fn(~2_#N0[ configuration B ]
!`c/?h^s m/b z0}51Testing软件测试网_3y:Ju-` `8A
location ^~ /images/ {
$gbZ ia]?0# matches any query beginning with /images/ and halts searching,
l&Tl3B-@&Y0# so regular expressions will not be checked.
%B0t9y Q M'p^y0# 匹配任何已 /images/ 开头的任何查询并且停止搜索。任何正则表达式将不会被测试
8zx?%X7X4{nE0[ configuration C ]
d1l H+ec o)zU8R0}
k:{E2v3H6l0location ~* ".(gif|jpg|jpeg)$ {51Testing软件测试网|.]rs6s"~f
# matches any request ending in gif, jpg, or jpeg. However, all51Testing软件测试网n/i;K ~_jk%SE
# requests to the /images/ directory will be handled by
3Q$|_}Ic{0# Configuration C.
6u&U/JJ-quL+b0# 匹配任何已 gif、jpg 或 jpeg 结尾的请求。然而所有 /images/ 目录的请求将使用 Configuration C。
Z%Zv0\L@\0[ configuration D ]51Testing软件测试网Kx"i~,?6M
}
51Testing软件测试网EFZ&En

如果要定义多个location,则可以有2种方式:

0F?x#DQEJ0
  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软件测试网1CsB%X,Py#|0k

 51Testing软件测试网.zN;i|;J}KeC

引用

 

(Fx7a*XU{9vPB0
  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软件测试网)\6KC_bEj\


TAG: nginx Nginx NGINX

 

评分:0

我来说两句

Open Toolbar