[nginx]location語法
阿新 • • 發佈:2018-03-11
正則表達 turn 字段 順序 html root 精確 cnblogs 默認
location語法
location語法格式
location [=|~|~*|^~] uri {
....
}
location [=|~|~*|^~] uri {....}
指令 匹配標識 匹配的網站地址 匹配URI後要執行的配置段
~ 與~* 的區別
location字段 | 說明 |
---|---|
~ | 匹配內容區分大小寫 |
~* | 匹配內容不區分的小寫 |
!~ | 取反 |
^~ | 但多個匹配同時存在,優先匹配 ^~匹配的內容;不做正則表達式的檢查 (優先處理) |
location官方示例
location = / { [ configuration A ] } location / { [ configuration B ] } location /documents/ { [ configuration C ] } location ^~ /images/ { [ configuration D ] } location ~* \.(gif|jpg|jpeg)$ { [ configuration E ] }
- 說明
"/" 請求將匹配配置A,
"/index.html" 請求將匹配配置B,
"/documents/document.html" 請求將匹配配置C,
"/images/1.gif" 請求將匹配配置D,
"/documents/1.jpg" 請求將匹配配置E.
按匹配順序
location = / { # 精確匹配 / [ configuration A ] } location ^~ /images/ { # 匹配常規字符串,不做正則表達式匹配檢查 [ configuration D ] } location ~* \.(gif|jpg|jpeg)$ { # 正則匹配 [ configuration E ] } location /documents/ { # 匹配常規字符串,如果有正則,則優先匹配正則 [ configuration C ] } location / { # 所有location 都不能匹配後的默認匹配 [ configuration B ] }
- 不同uri及特殊字符組合匹配的順序說明
測試location的訪問
修改返回值
server { listen 80; server_name www.maotai.com maotai.com; root html; location / { return 401; } location = / { return 402; } location /documents/ { return 403; } location ^~ /images/ { return 404; } location ~* \.(gif|jpg|jpeg)$ { return 500; } access_log logs/access_www.log main; }
[root@n1 ~]# curl -I -w "%{http_code}\n" -o /dev/null -s www.maotai.com/documents
401
[root@n1 ~]# curl -I -w "%{http_code}\n" -o /dev/null -s www.maotai.com
402
[root@n1 ~]# curl -I -w "%{http_code}\n" -o /dev/null -s www.maotai.com/documents/
403
[root@n1 ~]# curl -I -w "%{http_code}\n" -o /dev/null -s www.maotai.com/images/1.jpg
404
[root@n1 ~]# curl -I -w "%{http_code}\n" -o /dev/null -s www.maotai.com/documents/ss.jpg
500
[nginx]location語法