gpt4 book ai didi

带变量的 Nginx proxy_pass - 完整路径

转载 作者:行者123 更新时间:2023-12-02 03:18:48 25 4
gpt4 key购买 nike

最初我有一个这样的conf:

location /some/path/ {
proxy_pass http://other.host/foo/;
}

http://my.domain/some/path/bar的请求将被代理到http://other.host/foo/bar

我开始使用 proxy_pass 中的变量来强制 nginx 重新解析 DNS:

location /some/path/ {
resolver 1.2.3.4;
set $proxy_root "other.host/foo"
proxy_pass http://$proxy_root/;
}

但我发现 uri 路径的其余部分不再被附加,因此现在对 http://my.domain/some/path/bar 的请求将被简单地代理为 http://other.host/foo/.

所以我将其更改为正则表达式

location ~ ^/some/path/(.*) {
resolver 1.2.3.4;
set $proxy_root "other.host/foo"
proxy_pass http://$proxy_root/$1;
}

但是不包含任何查询参数,所以我再次更新

location ~ ^/some/path/(.*) {
resolver 1.2.3.4;
set $proxy_root "other.host/foo"
proxy_pass http://$proxy_root/$1?$args;
}

这有点管用,但这意味着有一个?在每个目标地址中,当只有部分传入请求实际上具有?查询部分...

我想我可以做一些进一步的字符串操作,但这感觉有点太多了。有没有像我最初那样更简单的 proxy_pass 方法,但将代理目标作为变量来强制重新解析?

最佳答案

除了使用位置匹配器之外,另一种选择是使用 $request_uri 并匹配您想要维护的部分。 $request_uri 包含完整的 URI,包括查询参数 ( http://nginx.org/en/docs/http/ngx_http_core_module.html#var_request_uri )。

由于location block 匹配/some/path/,因此使用正则表达式获取余数:

  if ($request_uri ~* "/some/path(/.*$)")
set $path_remainder $1;
}

最后,连接余数:

location /some/path/ {
resolver 1.2.3.4;
set $proxy_root "other.host/foo";
if ($request_uri ~* "/some/path(/.*$)") {
set $path_remainder $1;
}
proxy_pass http://$proxy_root$path_remainder;
}

至于为什么会出现这种情况,据http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass :

In some cases, the part of a request URI to be replaced cannot be determined

其中一个案例是

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.

这里就是这种情况,因为您的 proxy_pass 指令参数中有 $proxy_root 。

关于带变量的 Nginx proxy_pass - 完整路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30308786/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com