nginx根据url动态proxy_pass

oxf*_*ian 4 nginx nginx-reverse-proxy

目前,我的 nginx 配置文件中有以下代理传递定义:

location /pass/ {
    proxy_pass http://localhost:9999/pass/;
    proxy_redirect     off;
    proxy_set_header   Host $host;
}
Run Code Online (Sandbox Code Playgroud)

这按预期工作 - /pass 请求被转发到在端口 9999 上运行的应用程序。

现在,我想做的是将端口转发部分动态化,如下所示:

location /pass/<input> {
    {a $port variable here that is evaluated via a script (php?)}
    proxy_pass http://localhost:$port/pass/;
    proxy_redirect     off;
    proxy_set_header   Host $host;
}
Run Code Online (Sandbox Code Playgroud)

对 /pass/ABCD1234 的请求应转发到端口 9898,对 /pass/ABCD5678 的请求应转发到端口 9797。

请注意,该流程是动态的 - 因此,从 ABCD1234 到 9898 的映射应该通过某种脚本(也许是 PHP?)进行,并且基于脚本的输出(端口),proxy_pass 应该将请求转发到该端口。

请在这方面提供帮助。

更新 :

我不想从 URI 输入中获取 proxy_pass 端口,而是想通过 cookie 来实现这一点。所以,这是更新后的代码块:

location /pass/ {
    add_header X-debug-message $host always;
    add_header X-debug-message $cookie_sdmport;
    set $proxyurl http://127.0.0.1:$cookie_theport/pass/;
    add_header X-debug-message $proxyurl;
    proxy_pass $proxyurl;
    proxy_redirect     off;
    proxy_set_header   Host $host;
}
Run Code Online (Sandbox Code Playgroud)

使用此代码,会循环 301 重定向回浏览器。当我切换回静态端口时,它又可以工作了!奇怪的!X-debug-message 中的 $proxyurl 在浏览器上看起来是正确的。所以,想知道为什么 proxy_pass 会执行 301!

更新2:

最终使用以下设置进行转发:

    set $targetIP 127.0.0.1;
    set $targetPort $cookie_passport;
    proxy_pass http://$targetIP:$targetPort$request_uri;
Run Code Online (Sandbox Code Playgroud)

不知道为什么上面发布的解决方案不断旋转 301 - 我猜 nginx 不喜欢在 proxy_pass 参数中混合动态和静态部分

谢谢。

mik*_*nik 5

您可以使用该auth_request模块来完成此操作。虽然它不是默认构建的,但您可以通过运行以下命令来确定是否有它:

nginx -V 2>&1 | grep -qF -- --with-http_auth_request_module && echo ":)" || echo ":("
Run Code Online (Sandbox Code Playgroud)

如果您看到笑脸,那么就可以开始了。

location ~* /pass/(.*) { <- regex capture for your variable
    auth_request /auth;  <- location to process request
    auth_request_set $proxyurl http://localhost:$upstream_http_x_port/pass/; <- set $proxyurl using value returned in x-port header of your php script
    add_header x-my-variable $1; <- Pass variable from regex capture to auth location
    proxy_pass $proxyurl;
}
Run Code Online (Sandbox Code Playgroud)

然后是处理身份验证子请求的位置:

location /auth {
    internal; <- make location only accessible to internal requests from Nginx
    proxy_set_header x-my-variable $http_x_my_variable; <- pass variable to php
    proxy_pass_request_body off; <- No point sending body to php
    proxy_set_header Content-Length "";
    proxy_pass http://your-php-script/file.php;
}
Run Code Online (Sandbox Code Playgroud)

这个模块实际上是用于访问控制的,所以如果你的php脚本返回响应代码200,那么客户端将被允许访问,如果它返回401或403,那么访问将被拒绝。如果你不关心这个,那么只需将其设置为始终返回 200 即可。

进行您需要的任何评估,并让您的 php 返回之前定义的标头中的端口:

header('X-Port: 9999');
Run Code Online (Sandbox Code Playgroud)

现在为您的 proxy_pass 指令端口号设置变量,Nginx 完成其余的工作。