Kong API 网关 v0.11.0 upstream_url

我们正在尝试设置一个依赖于请求头的插件,将其代理到特定的主机。例如:

curl -H 'Env: foo' http://127.0.0.1:8000/poc -> https://foo.example.com/poc
curl -H 'Env: bar' http://127.0.0.1:8000/poc -> https://bar.example.com/poc

在早期版本(< v0.11.0)中,以下代码工作正常(这是我们插件的access.lua文件):

local singletons = require "kong.singletons"
local responses = require "kong.tools.responses"

local _M = {}

function _M.execute(conf)
  local environment = ngx.req.get_headers()['Env']

  if environment then
    local result, err = singletons.dao.environments:find_all {environment = environment}

    if err then
      return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
    else
      ngx.ctx.upstream_url = result[1].proxy_redirect
    end

  end
end

return _M

这是由于ngx.ctx.upstream_url覆盖了proxy_pass行为。

由于我们想要在k8s环境中使用它,所以我们必须使用0.11.0版本,因为他们修复了一些关于dns的问题。问题似乎是他们已经把ngx.ctx.upstream_url改成了ngx.var.upstream_uri,但行为不同,它不会改变代理请求的主机。这是我们得到的错误:

2017/08/23 11:28:51 [error] 22#0: *13 invalid port in upstream "kong_upstreamhttps://foo.example.com", client: 192.168.64.1, server: kong, request: "GET /poc HTTP/1.1", host: "localhost:8000"

有人遇到相同的问题吗?有没有其他解决办法?

非常感谢。

点赞
用户8506022
用户8506022

如果有人对此感兴趣,这是我解决这个问题的方式。

最后,我通过“Host”头进行了重定向,并在我的插件中更改了头以适应其他api。我的意思是:

我创建了2个API:

curl -H 'Host: foo' http://127.0.0.1:8000/ -> https://foo.example.com
curl -H 'Host: bar' http://127.0.0.1:8000/ -> https://bar.example.com

我的插件行为应该像这样:

curl -H 'Host: bar' -H 'Env: foo' http://127.0.0.1:8000/poc -> https://foo.example.com/poc
curl -H 'Host: foo' -H 'Env: bar' http://127.0.0.1:8000/poc -> https://bar.example.com/poc

最重要的是,您应该在handler.lua文件中使用rewrite上下文,而不是access上下文:

function ContextRedirectHandler:rewrite(conf)

  ContextRedirectHandler.super.rewrite(self)
  access.execute(conf)

end

然后,您可以在access.lua文件中像这样更改“Host”头:

local singletons = require "kong.singletons"
local responses = require "kong.tools.responses"

local _M = {}

function _M.execute(conf)
  local environment = ngx.req.get_headers()['Env']

  if environment then
    local result, err = singletons.dao.environments:find_all {environment = environment}

    if err then
      return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
    else
      ngx.req.set_header("Host", result[1].host_header_redirect)
    end

  end
end

return _M
2017-08-25 13:14:17