URI

Nginx 用 location 块为不同的请求 URI 设置配置。正如 Nginx.org 所说:

匹配是针对规范化后的 URI 进行的:先解码以 “%XX” 形式编码的文本,解析相对路径成分 “.” 和 “..”,并可能把两个或更多相邻的斜杠压缩成一个斜杠。

location 语法

Nginx location 块的一般结构是

location optional_modifier location_match {
    # contents
}

或者记作

location [ = | ~ | ~* | ^~ ] uri { ... }
location @name { ... }

optional_modifier 告诉 nginx 用哪种匹配方式检查 location_match(也记作 uri)是否与请求的 URI 匹配。修饰符主要有五种,优先级从高到低依次是:= > ^~ > ~ = ~* > none。

修饰符

^~ = none 表示该 location 由前缀字符串定义。

~ 和 ~* 表示该 location 由正则表达式定义,其中 ~ 区分大小写,~* 不区分大小写。

优先级

Nginx 首先检查由前缀字符串定义的 location(即 ^~ = none),也就是检查 URI 是否以 uri 开头

  • 如果找到 = 的精确匹配,即 URI=uri,搜索结束;否则继续前缀检查。
  • 选出并记住与 URI 匹配的最长的 uri。
  • 所有前缀字符串都处理完之后,如果最长匹配的前缀 location(最长的 uri)由 ^~ 指定,就跳过后面的正则检查,搜索结束;否则转入**正则**搜索。

然后,Nginx 按照正则表达式在配置文件中出现的顺序逐一检查。

  • 正则表达式的搜索在第一次匹配时结束,并使用对应的配置。
  • 如果没有任何正则表达式匹配,就使用前面记住的那个前缀 location 的配置。

提示:Nginx 文档中写道:

如果找到精确匹配,搜索就会结束。例如,如果 “/” 请求很频繁,定义 “location = /” 可以加快这些请求的处理,因为第一次比较之后搜索就结束了。

示例

Martin Redmond 总结如下:

location  = / {
  # matches the query / only.
  [ configuration A ] 
}
location  / {
  # matches any query, since all queries begin with /, but regular
  # expressions and any longer conventional blocks will be
  # matched first.
  [ configuration B ] 
}
location /documents/ {
  # matches any query beginning with /documents/ and continues searching,
  # so regular expressions will be checked. This will be matched only if
  # regular expressions don't find a match.
  [ configuration C ] 
}
location ^~ /images/ {
  # matches any query beginning with /images/ and halts searching,
  # so regular expressions will not be checked.
  [ configuration D ] 
}
location ~* \.(gif|jpg|jpeg)$ {
  # matches any request ending in gif, jpg, or jpeg. However, all
  # requests to the /images/ directory will be handled by
  # Configuration D.   
  [ configuration E ] 
}

参考

How nginx processes a request

Module ngx_http_core_module


0 条评论

发表回复

Avatar placeholder

您的邮箱地址不会被公开。 必填项已用 * 标注