proxy_pass 覆盖由重写指令更改的 URL

proxy_pass overwrites the URL changed by rewrite directive

从下面引用的 nginx documentation,我了解到 proxy_pass 指令不会更改 URI,只会将重写的 URI 传递给服务器。

  • When the URI is changed inside a proxied location using the rewrite directive, and this same configuration will be used to process a request (break):

    location /name/ {
        rewrite    /name/([^/]+) /users?name= break;
        proxy_pass http://127.0.0.1/randomstring;
    }
    

    In this case, the URI specified in the directive is ignored and the full changed request URI is passed to the server.

但是当我将 proxy_pass 设置为变量时,URI 被覆盖。

示例:

location /test_rewrite {
    set $ups_addr http://upstream_server;
    rewrite /test_rewrite /test_rewrite_upstream break;
    proxy_pass $ups_addr/random_string;
}

正在将 URI /test_rewrite 重写为 /random_string

任何人都可以帮我理解这种行为的原因吗?

正如下面相同的文档所述:

  • When variables are used in proxy_pass:

    location /name/ {
        proxy_pass http://127.0.0.1$request_uri;
    }
    

    In this case, if URI is specified in the directive, it is passed to the server as is, replacing the original request URI.

仅当结果字符串包含 URI 部分时才为真。一些例子:

location /test_rewrite {
    set $ups_addr http://upstream_server;
    rewrite /test_rewrite /test_rewrite_upstream break;
    proxy_pass $ups_addr;
}

结果字符串不包含 URI 部分,传递给上游服务器的 URI 是 /test_rewrite_upstream

location /test_rewrite {
    set $ups_addr http://upstream_server/;
    rewrite /test_rewrite /test_rewrite_upstream break;
    proxy_pass $ups_addr;
}

结果字符串包含 URI 部分(注意 $ups_addr 变量末尾的斜杠),传递给上游服务器的 URI 是 /.

您可以使用 $uri 变量将重写规则与 proxy_pass 指令中的自定义 URI 部分结合起来:

location /test_rewrite {
    set $ups_addr http://upstream_server;
    rewrite /test_rewrite /test_rewrite_upstream break;
    proxy_pass $ups_addr/random_string$uri;
}

在这种情况下,传递给上游服务器的 URI 是 /random_string/test_rewrite_upstream

要保留请求参数,请使用 $is_args and $args 变量:

location /test_rewrite {
    set $ups_addr http://upstream_server;
    rewrite /test_rewrite /test_rewrite_upstream break;
    proxy_pass $ups_addr$uri$is_args$args;
}