nginx location配置小结

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012949658/article/details/75418573

location 语法:location [=|\~|\~*|^~|@] /uri/ { … }
默认:否
上下文:server
这个指令随URL不同而接受不同的结构,既可以配置常规字符串也可以使用正则表达式。如果使用正则表达式,必须使用\~*或者是\~作为前缀,两者的区别是\~*不区分大小写,~是区分大小写的。

那么多的location,判定的顺序是什么呢?

  1. 先匹配普通的location,然后再匹配正则表达式。
  2. 普通的location之间,匹配最大前缀。因为location不是“严格匹配”而是“前缀匹配”,就会产生一个HTTP请求可以“前缀匹配”到多个location,举例来说:如果HTTP请求/prefix/mid/t.html,location /prefix/mid/ {} 和location /prefix/ {}都满足匹配要求,选哪个呢?使用最大前缀匹配,使用location /prefix/mid/ {}。
  3. 正则location匹配的时候,按照配置文件的先后顺序进行匹配,并且只要匹配到一条正则location就不考虑后面的。
  4. 匹配完了普通的location之后,会形成一个临时结果,然后继续正则匹配,,如果有匹配上的,就会“覆盖”之前临时的结果;正则location里如果没有匹配的上的,就使用最大前缀匹配的结果。
  5. 通常的规则是匹配完了普通location之后,再去匹配正则location,能不能直接匹配完了普通location之后,不再匹配正则location了?可以使用“\^\~”或者“=”实现,^表示非,\~表示正则,使用“\^\~”作为前缀的意思就是不用继续匹配正则,并且“\^\~”依然遵守最大前缀匹配规则;“=”则是必须严格匹配。
  6. 前面说到可以使用“\^\~”或者“=”阻止正则location的搜索,其实还有一种“隐含”的方式,那就是location的配置精确到直接匹配,比如说当前的配置为location /exact/match/test.html {配置指令块1},那么当我们请求GET /exact/match/test.html,就会匹配到指令块1,不再继续搜索!(还未验证!)

顺便说一下“location / {}”和“location = / {}”的区别,“location / {}”遵守普通location最大前缀匹配,因为任何URI都必然以“/”根开头,所以能匹配任何URI,如果有更具体的location就选具体的,如果没有,“location / {}”也能起到一个保底的作用;“location = / {}”遵守的是严格精确匹配,也就是智能匹配http://host:port/请求,同时会禁止继续搜索正则location。如果我们只想对“GET /”请求配置作用指令,那么我们可以使用“location = / {}”减少正则location的搜索,提高效率。

To summarize, the order in which directives are checked is as follows:

  1. Directives with the “=” prefix that match the query exactly. If found, searching stops.
  2. All remaining directives with conventional strings. If this match used the “^~” prefix, searching stops.
  3. Regular expressions, in the order they are defined in the configuration file.
  4. If #3 yielded a match, that result is used. Otherwise, the match from #2 is used.

翻译过来就是:
1. = 前缀的指令严格匹配这个查询。如果找到,停止搜索;
2. 剩下的常规字符串,长的在前。如果这个匹配使用 ^~ 前缀,搜索停止;
3. 正则表达式,按配置文件里的顺序;
4. 如果第三步产生匹配,则使用这个结果。否则使用第二步的匹配结果。

配置举例:

location = / {
# 只匹配/查询。
[ configuration A ]
}
location / {
# 匹配任何查询,因为所有请求都以/开头。但是正则表达式规则和长的块规则将被优先和查询匹配。
[ configuration B ]
}
location ^~ /images/ {
# 匹配任何已 /images/ 开头的任何查询并且停止搜索。任何正则表达式将不会被测试。
[ configuration C ]
}
location ~* \.(gif|jpg|jpeg)$ {
# 匹配任何已 gif、jpg 或 jpeg 结尾的请求。然而所有 /images/ 目录的请求将使用 Configuration C。
[ configuration D ]
}

请求举例:

/ -> configuration A
/documents/document.html -> configuration B
/images/1.gif -> configuration C
/documents/1.jpg -> configuration D

注意:按任意顺序定义这4个配置结果将仍然一样

参考资料: 关于一些对location认识的误区
官方文档解释:http://wiki.nginx.org/NginxHttpCoreModule#location

猜你喜欢

转载自blog.csdn.net/u012949658/article/details/75418573
今日推荐