官方文档 http://nginx.org/en/docs/http/ngx_http_core_module.html#location
location可以理解为路由规则,可以通过请求前缀等信息将不同请求进行不同的处理。
配置语法
Syntax: location [ = | ~ | ~* | ^~ ] uri { ... }
location @name { ... }
Default: —
Context: server, location
前缀修饰符
=
:精确匹配~
:区分大小写的正则匹配~*
:不区分大小写的正则匹配^~
:不使用正则匹配- 无修饰符:前缀匹配
匹配优先级及规则
优先级
=
修饰符的优先级最高。^~
修饰符次之。~
、~*
修饰符第三。- 无修饰符的优先级最低。(采用前缀匹配)
通常来说,location分为两类:
普通location:含有 =
、^~
修饰符或者无修饰符。相应的匹配规则是前缀匹配。
正则location:含有 ~
、~*
修饰符。相应的匹配规则是正则匹配。
规则:
- 对于普通location,使用最长前缀匹配原则来选择最终生效的location。即当一个请求能同时匹配多个location时,则使用匹配表达式最长的那个location。
- 对于正则location,使用优先定义原则来选择最终生效的location。即当一个请求能同时匹配多个location时,则按配置文件中的定义顺序,从上往下,优先采用上面的。
示例
location = / {
# 仅匹配请求 /
default_type text/html; return 200 A;
}
location / {
# 前缀匹配所有以 / 开头的请求。
}
location /documents/ {
# 前缀匹配所有以 /documents/ 开头的请求。
}
location ^~ /images/ {
# 前缀匹配所有以 /images/ 开头的表达式。
}
location ~* \.(gif|jpg|jpeg)$ {
# 正则匹配所有以 gif jpg jpeg结尾的请求。
}
最佳拍档
root 指令:指定静态目录
官方文档 http://nginx.org/en/docs/http/ngx_http_core_module.html#root
Syntax: root path;
Default: root html;
Context: http, server, location, if in location
默认值为 html
。如果 path 不是绝对路径,则是相对于Nginx的安装目录的路径。
index 指令:指定默认文件
官方文档 http://nginx.org/en/docs/http/ngx_http_index_module.html
Syntax: index file ...;
Default: index index.html;
Context: http, server, location
默认值为 index.html
。可指定多个文件,允许包含路径、变量。
try_files 指令:指定文件查找规则
pass_proxy 指令:指定代理地址
end