如何在 nginx 中使用 url 路径名作为上游哈希

how to use url pathname as upstream hash in nginx

我有一个 nginx 服务器配置使用 queryparam 作为上游散列。 Url 看起来像下面

http://www.my-server.com/xyz/WXYZ?abc=123

配置如下

upstream test {
    hash $arg_abc;
    ....
}

是否有可能使用 URL 的 WXYZ 部分作为上游哈希?

WXYZ 是动态值,xyz 始终相同并且会存在。

这是我试过的,

location ~ ^/xyz/(.).*$ {
   hash 
}

是的,根据 hash 的文档,您只能在 upstream 上下文中使用它,因此您尝试过的方法确实无效。

但是,如果其他部分保持不变,那么为什么您只需要使用 URI 中的特定路径而不是整个路径呢?我认为这个想法是整个字符串无论如何都应该被进一步散列,所以,即使你所有的 URL 开始相同,散列函数仍然应该均匀分布所有内容。因此,您很可能只使用 $request_uri$uri 作为哈希。

或者,如果您仍想按照自己的方式进行,您可以尝试在 location (location ~ ^/xyz/(?<varForHash>.).*$ {…) 中使用命名模式匹配,然后使用此类匹配中的变量 ($varForHash) 作为您的 hash(您甚至可以在示例中使用 </code>,只是在适当的上下文中 — <code>upstream)。

The deployment guide明确表示有可能:

The generic hash method: the server to which a request is sent is determined from a user-defined key which may be a text, variable, or their combination. For example, the key may be a source IP and port, or URI:

upstream backend {
    hash $request_uri consistent;

    server backend1.example.com;
    server backend2.example.com;
}

hash key是$request_uri可以用$arg_your_key代替但不确定是与上游块一起工作,但它应该作为 proxy_pass 值:

location /xyz {
  proxy_pass http://localhost/$uri$is_args$args;
}

不确定要求,但如果您需要使用基于参数 $arg_abc 的特定后端,您需要映射函数,例如 here:

map $arg_abc $backend_server {
 default  'serverdefault.domain.com:80';
 123 'server1.domain.com:80';
 234 'server2.domain.com:80';
 345 'server3.domain.com:80';
}

server {
 location / {
  proxy_pass http://$backend_server;
 }
}

我遇到了类似的任务,我解决了。 我创建了 upstream.conf 并将其添加到 nginx.conf。 upstream.conf内容如下:

map $uri $myvar{
    default $uri;
    # pattern "Method1" + "/" + GUID + "/" + target parameter + "/" + HASH;
    "~*/Method1/(.*)/(.*)/(.*)$" ;
    # pattern "Method2" + "/" + GUID + "/" + target parameter;
    "~*/Method2/(.*)/(.*)$" ;
}


upstream backend {
    hash $myvar consistent;
    server s1:80;
    server s2:80;
}