简体   繁体   English

路径中间带有正则表达式的 Nginx 位置

[英]Nginx location with regex in the middle of path

i'm trying to configure Nginx to parse correctly two similar paths with a regex in it.我正在尝试配置 Nginx 以正确解析两个包含正则表达式的相似路径。

I have 2 services:我有 2 项服务:

  • /api/v1/myservice/{var}/client /api/v1/myservice/{var}/client
  • /api/v1/myservice/{var}/client/detail /api/v1/myservice/{var}/client/detail

{var} is a variable I'm reading which is working {var} 是我正在阅读的一个正在工作的变量

Here my code (not using the var here):这是我的代码(此处不使用 var):

location ~ /api/v1/myservice/(.*)/client {
     return 200 "service 1 ";
}

location ~ /api/v1/myservice/(.*)/client/detail {
     return 200 "service 2";
}

When I run curl like the following:当我像下面这样运行 curl 时:

curl http://localhost/api/v1/myservice/623723852/client/detail

I see the response from the first location: "Service 1"我看到来自第一个位置的响应:“服务 1”

What Am I doing wrong?我究竟做错了什么? thanks谢谢

No need to have nested locations as in the other answer.不需要像另一个答案中那样嵌套位置。 The nested locations in NGINX often give a false impression about directives' inheritance. NGINX 中的嵌套位置经常给人一种关于指令继承的错误印象。 More often than not, they are not inherited, because NGINX chooses one specific location anyway.通常情况下,它们不会被继承,因为 NGINX 无论如何都会选择一个特定的location For these reasons, if you can, avoid nested locations.出于这些原因,如果可以,请避免嵌套位置。

You can simply change the order of locations so that the more specific one goes first.您可以简单地更改位置的顺序,以便更具体的位置在前。 NGINX will match the one that appears first in the config (if they both match): NGINX 将匹配配置中第一个出现的(如果它们都匹配):

location ~ /api/v1/myservice/(.*)/client/detail {
     return 200 "service 2";
}

location ~ /api/v1/myservice/(.*)/client {
     return 200 "service 1 ";
}

Alternatively, somewhat better (for performance reasons), you can adjust your regexes for more exact matching.或者,稍微好一点(出于性能原因),您可以调整正则表达式以获得更精确的匹配。 Then the placement in configuration won't matter:然后在配置中的位置无关紧要:

location ~ ^/api/v1/myservice/(.*)/client$ {
     return 200 "service 1 ";
}

location ~ ^/api/v1/myservice/(.*)/client/detail$ {
     return 200 "service 2";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM