基于url pa的nginx dynamic proxy_pass

问题描述 投票:2回答:1

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

location /pass/ {
    proxy_pass http://localhost:9999/pass/;
    proxy_redirect     off;
    proxy_set_header   Host $host;
}

这是按预期工作 - /传递请求被转发到在端口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;
}

对/ 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;
}

使用此代码,循环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;

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

谢谢。

nginx nginx-reverse-proxy
1个回答
2
投票

您可以使用auth_request模块执行此操作。它不是默认构建的,你可以通过运行以下命令找出它是否有它:

nginx -V 2>&1 | grep -qF -- --with-http_auth_request_module && echo ":)" || echo ":("

如果你看到笑脸,那么你很高兴。

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;
}

然后是处理auth子请求的位置:

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;
}

此模块实际上用于访问控制,因此如果您的php脚本返回响应代码200,则允许客户端访问,如果它返回401或403,则访问将被拒绝。你不关心那个,然后把它设置为总是返回200。

做你需要的任何评估,让你的php返回前面定义的头文件中的端口:

header('X-Port: 9999');

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

© www.soinside.com 2019 - 2024. All rights reserved.