0%

Nginx location 匹配规则

location 匹配规则

1
2
3
4
Syntax: location [ = | ~ | ~* | ^~ ] uri { ... }
location @name { ... }
Default: —
Context: server, location

location 分类

  • 前缀字符串匹配

    1
    location [=|^~] uri {...}
    • =
      完全匹配/精确匹配
    • ^~
      前缀匹配
    • “无任何特殊字符”
      从前往后,普通匹配
  • 正则匹配

    1
    location [~*|~] uri {...}
    • ~
      匹配区分大小写
    • ~*
      匹配不区分大小写
  • 其他

    1
    location @ uri {...}

只用于内部重定向

匹配步骤

  1. 先将所有“前缀字符串匹配”匹配一遍,选出一个“最长匹配”,将结果暂存起来。

    若“最长匹配” 以 [^~|=] (完全匹配或前缀匹配)标示,立即终止匹配,并返回。不继续进行下面匹配

  2. 按配置中书写顺序依次进行“正则匹配”,遇到第一个合法的匹配则不继续向下匹配

匹配结果选择

一个成功的匹配,1个或0个“前缀字符串匹配”,1个或0个“正则匹配”

  • 有“正则匹配”,选“正则匹配”
  • 没有“正则匹配”,选“前缀字符串匹配”
  • 都没有,则报错

Others

If a location is defined by a prefix string that ends with the slash character, and requests are processed by one of proxy_pass, fastcgi_pass, uwsgi_pass, scgi_pass, or memcached_pass, then the special processing is performed. In response to a request with URI equal to this string, but without the trailing slash, a permanent redirect with the code 301 will be returned to the requested URI with the slash appended. If this is not desired, an exact match of the URI and location could be defined like this:

1
2
3
4
5
6
7
location /user/ {
proxy_pass http://user.example.com;
}

location = /user {
proxy_pass http://login.example.com;
}

简单翻译一下:
对于

1
2
3
location /user/ {
proxy_pass http://user.example.com;
}

若请求为 /user,则请求将被转发到 http://user.example.com/user/
注意此时 /user 后面被加上了 ‘/‘,如果这种情况不是我们预期的,可以显示声明一种完全匹配处理 /user。
既:

1
2
3
location = /user {
proxy_pass http://login.example.com;
}

5. Reference & Thanks