from:
Nginx的Location可以有以下幾個(gè)匹配:
1. = 嚴(yán)格匹配這個(gè)查詢。如果找到,停止搜索。
2. ^~ 匹配路徑的前綴,如果找到,停止搜索。
3. ~ 為區(qū)分大小寫的正則匹配
4. ~* 為不區(qū)分大小寫匹配
例子:
location = / {
# matches the query / only.
# 只匹配 / 查詢。
[ configuration A ]
}
location / {
# matches any query, since all queries begin with /, but regular
# expressions and any longer conventional blocks will be
# matched first.
# 匹配任何查詢,因?yàn)樗姓埱蠖家?/ 開頭。但是正則表達(dá)式規(guī)則和長的塊規(guī)則將被優(yōu)先和查詢匹配。
[ configuration B ]
}
location ^~ /images/ {
# matches any query beginning with /images/ and halts searching,
# so regular expressions will not be checked.
# 匹配任何已 /images/ 開頭的任何查詢并且停止搜索。任何正則表達(dá)式將不會被測試。
[ configuration C ]
}
location ~* ".(gif|jpg|jpeg)$ {
# matches any request ending in gif, jpg, or jpeg. However, all
# requests to the /images/ directory will be handled by
# Configuration C.
# 匹配任何已 gif、jpg 或 jpeg 結(jié)尾的請求。然而所有 /images/ 目錄的請求將使用 Configuration C。
[ configuration D ]
}
如果要定義多個(gè)location,則可以有2種方式:
- 使用/ :
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可以放在/的下面,因?yàn)?#8220;/是匹配任何查詢,但是正則表達(dá)式規(guī)則和長的塊規(guī)則將被優(yōu)先和查詢匹配”
- 使用~ /* :
location ~ /tmp/ { root /tmp; internal; } location ~ /* { client_max_body_size 20m; proxy_connect_timeout 30; fastcgi_pass fpass; include fastcgi_params; }
采用這種方式,/tmp則必須放在~ /*這個(gè)前面,因?yàn)閪是正則匹配的,正則匹配是有順序的,只要匹配上就不會再往下匹配了。除非在conf中有定義=或者^~,也就是說=和^~的優(yōu)先級最高,如果匹配上,就不會再去匹配其它的規(guī)則了。
總之,引用Nginx的官方文檔的匹配規(guī)則:
引用
- 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.
注意:正則表達(dá)式的匹配是有順序的,按順序匹配。其它的匹配理論上講是只有優(yōu)先級,而沒有順序的。