4

We are trying to set up a plugin that depends on the headers of the request, proxy it to an specific host. Ex.

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

In early versions (< v0.11.0) the following code worked (this is our access.lua file of the plugin):

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

This worked due to ngx.ctx.upstream_url overwrote the proxy_pass behavior.

As we want to use it in k8s environment, we had to use 0.11.0 version because they have fixed some issues regarding to dns. The problem seems to be they have changed ngx.ctx.upstream_url by ngx.var.upstream_uri, but the behavior is not the same, it does not change the host to proxy our request. This is the error we get:

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"

Does anyone have the same problem? Is there any other solution to our problem?

Thank you very much in advance.

1 Answers1

4

This is the way I solved this issue if someone is interested on it.

Finally, I did a redirection by "Host" header, and what I did in my plugin was change the header for suiting the other api. I mean:

I created 2 APIs:

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

And the behavior of my plugin should be like this:

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

The most important think is that you should use in the handler.lua file the rewrite context instead of the access context:

function ContextRedirectHandler:rewrite(conf)

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

end

And then, you can change the "Host" header in your access.lua file like this:

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