【问题标题】:Nginx proxy_pass to a variable urlNginx proxy_pass 到变量 url
【发布时间】:2015-05-20 09:36:11
【问题描述】:

我是 Nginx 的新手。据我所知,我们可以在 nginx.conf 中配置 proxy_pass url,如:

location /test
{
     proxy_pass http://10.10.10.10:10000;
}

但是现在,我需要将 proxy_pass 传递给一个变量 url,我们可以在 http 请求头或请求正文中获取这个 url(例如)。

我该如何实现呢?感谢您的帮助!

编辑1(解释我的问题):

有一个http请求,其标头中有一个名为“redirectUrl”的参数发送到Nginx,我只想让Nginx修改这个http请求头,然后将此请求发送到redirectUrl。因为redirectUrl是一个变量,所以我猜“proxy_pass $request”可以实现这个,但我不知道怎么做。谁能给我一个提示或有任何文档?

编辑2:

我试过 ngx_lua :

location /apiproxytest {

    set_by_lua $redirectURL '
            return ngx.req.get_headers()["Host"]
    ';

    header_filter_by_lua '
             ngx.header["RedirectURL"] = nil;
             ngx.header["Host"] = nil;
    ';

    echo "1:" $redirectURL;

    set_by_lua $redirectURL2 '
            return ngx.req.get_headers()["Host"]
    ';

    echo "2:" $redirectURL2;

    #proxy_pass $redirectURL;
}   

我发现 echo 1 和 echo 2 是相同的,正如 ngx.header.HEADER 解释的那样,ngx.header["Host"] = nil 应该删除 http 请求标头中的 Host。为什么 echo "2:" $redirectURL2 也能打印 Host 的值?

【问题讨论】:

  • 您阅读过文档吗? nginx.org/r/proxy_pass
  • @AlexeyTen 感谢您的帮助,我已经阅读了文档,但它只告诉我可以,没有怎么做。你能帮我一把吗?

标签: nginx


【解决方案1】:

试试ngx_lua

set_by_lua 中的ngx.req.get_headers 获取redirectUrl,然后设置为$redirectURL,最后设置为proxy_pass $redirectURL

追加编辑 2:

为什么 echo 1 和 echo 2 是一样的?

这是由 Nginx 引起的Phases

setset_by_luarewrite 阶段工作,echocontent 阶段工作,header_filter_by_luaoutput-header-filter 阶段(doc)工作,这是内容的背后。

你的配置是这样工作的:

set_by_lua -> set_by_lua -> echo 1 -> echo 2 -> header_filter_by_lua.

【讨论】:

  • 谢谢!我已经编辑了使用 ngx_lua 的新问题。请帮帮我~
  • @SomnusLee 我附上了我的答案,希望对你有所帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-03
  • 1970-01-01
  • 2015-11-08
  • 2013-06-04
  • 1970-01-01
相关资源
最近更新 更多