Skip to content

Instantly share code, notes, and snippets.

@imzhi
Forked from luxixing/nginx-location
Created April 7, 2016 02:20
Show Gist options
  • Save imzhi/b536f37f8df79c05c94fe2880b9a1d78 to your computer and use it in GitHub Desktop.
Save imzhi/b536f37f8df79c05c94fe2880b9a1d78 to your computer and use it in GitHub Desktop.
nginx location 匹配规则
1 普通匹配,遵循最长匹配规则,假设一个请求匹配到了两个普通规则,则选择匹配长度大的那个
例如:
location /{
[matches]
}
location /test{
[matches]
}
2 精确匹配
location = /{
[matchtes]
}
location = /test{
[matches]
}
3 正则匹配
~ 区分大小写的匹配
location ~ ^*.php${
[matches]
}
~* 不区分大小写的匹配
location ~* ^*.php${
[matches]
}
^~ 普通字符匹配,如果请求匹配此规则,则其他规则忽略,只匹配该规则
location ^~ /test{
[matches]
}
4 @locationname 内部redirect匹配
location @locationname{
[matches]
}
匹配优先级:
首先检查是否有精确匹配规则,如果有,则处理精确匹配规则,假设发现精确匹配规则,停止搜索其他匹配规则,返回当前匹配的规则
其次普通字符匹配,该项匹配请求,仍然需要检查是否有正则或者更长匹配,如果有,返回正则匹配或者更长匹配
^~匹配被第三步处理,如果请求匹配此规则,停止其他规则匹配,返回此规则
正则匹配被最后执行,正则匹配只要被找到,停止解析其他规则,这个就要注意先后顺序了
完整的例子:
location = / {
# 只匹配"/".
[ configuration A ]
}
location / {
# 匹配任何请求,因为所有请求都是以"/"开始
# 但是更长字符匹配或者正则表达式匹配会优先匹配
[ configuration B ]
}
location ^~ /images/ {
# 匹配任何以 /images/ 开始的请求,并停止匹配 其它location
[ configuration C ]
}
location ~* \.(gif|jpg|jpeg)$ {
# 匹配以 gif, jpg, or jpeg结尾的请求.
# 但是所有 /images/ 目录的请求将由 [Configuration C]处理.
[ configuration D ]
}
请求URI例子:
/ -> 符合configuration A
/documents/document.html -> 符合configuration B
/images/1.gif -> 符合configuration C
/documents/1.jpg ->符合 configuration D
@location 例子
error_page 404 = @fetch;
location @fetch{
proxy_pass http://fetch;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment