location 作用
location 指令的作用是根據用戶請求的 URI(路徑) 來匹配不同的配置。其實就是根據用戶請求的網站地址 URL 進行匹配,匹配成功即進行相關的操作。
location 語法
location 使用的語法為:
location [ = | ~ | ~* | ^~ ] uri { ... }
語法各部分含義:
| location | [ = | ~ | ~* | ^~ | @ ] |
URI | { ... } |
|---|---|---|---|
| 指令 | 匹配標識 | 匹配的網站網址 | 匹配URI后要執行的配置段 |
每個匹配標識的作用:
| 匹配標識 | 作用 |
|---|---|
| ~* | 正則匹配,不區分大小寫 |
| ~ | 正則匹配,區分大小寫 |
| ^~ | 優先匹配常規字符串,不使用正則匹配 |
| = | 精確匹配,比如,如果請求“/”出現頻繁,定義“location = /”可以提高這些請求的處理速度 |
| @ | 定義命名路徑,用在請求重定向中 |
location 示例
location = / {
[ configuration A ] # 當用戶請求 http://www.abc.com/ 時執行配置A
}
location / {
[ configuration B ] # 當用戶請求 http://www.abc.com/ 時執行配置B
}
location /documents {
[ configuration C ] # 當用戶請求 http://www.abc.com/documents/document.html 時執行配置C
}
location ^~ /images/ {
[ configuration D ] # 當用戶請求 http://www.abc.com/images/1.gif 時執行配置D
}
location ~* \.(gif|jpg|jpeg)$ {
[ configuration E ] # 當用戶請求 http://www.abc.com/documents/1.jpg 時執行配置E
}
location 匹配實戰
虛擬主機配置:
server {
listen 80;
server_name www.abc.com abc.com;
root html/www;
location / { # " / " 表示所有 location 都不能匹配后才匹配這個
return 401; # 當用戶請求 http://www.abc.com/index.html 時返回 401
}
location = / { # " = / " 表示精確匹配
return 402; # 當用戶請求 http://www.abc.com/ 時返回 402
}
location /documents/ { # " /documents/ " 表示匹配常規字符,如果有正則,則優先匹配正則
return 403; # 當用戶請求 http://www.abc.com/documents/document.html 時返回 403
}
location ^~ /images/ { # " ^~ /images/ " 表示匹配常規字符串,不做正則匹配檢查
return 404; # 當用戶請求 http://www.abc.com/images/1.gif 時返回 404
}
location ~* \.(gif|jpg|jpeg)$ { # " ~* \.(gif|jpg|jpeg)$ " 表示正則匹配
return 500; # 當用戶請求 http://www.abc.com/documents/1.jpg 時返回 500
}
}
實驗結果:
curl -s -o /dev/null -I -w "%{http_code}\n" http://www.abc.com/index.html
401
curl -s -o /dev/null -I -w "%{http_code}\n" http://www.abc.com/
402
curl -s -o /dev/null -I -w "%{http_code}\n" http://www.abc.com/documents/document.html
403
curl -s -o /dev/null -I -w "%{http_code}\n" http://www.abc.com/images/1.gif
404
curl -s -o /dev/null -I -w "%{http_code}\n" http://www.abc.com/documents/1.jpg
500
通過以上多個 location 的匹配可以看出匹配的優先順序。
參考資料
http://tengine.taobao.org/nginx_docs/cn/docs/http/ngx_http_core_module.html#location
