Nginx – Passthrough captured request in nginx with lua

luanginx

I'm doing something like this:

location /foo {
        content_by_lua_block {
            local reqType = ngx.var.request_method
            if reqType == "POST"
                res = ngx.location.capture("/bar")
            else
                res = ngx.location.capture("/baz")
            end
            ngx.say(res.body)
        }
    }

    location /bar {
        internal;
        #fastcgi, omitted
    }

    location /baz{
        internal;
        #fastcgi, omitted
    }
}

But the headers sent by PHP are lost and status code is always 200. Is there anyway to just send the original response? ngx.say() just output the response body, and I need to capture the entire request and send it to browser.

I'm using openresty/1.9.15.1

Edit: I found a way to do this, but if there exists any different way to do this, would be very appreciated.

Best Answer

This is possible using response properties:

response = ngx.location.capture("/bar")
for headerName, header in pairs(response.header) do
    ngx.header[headerName] = header
end
ngx.status = response.status
ngx.say(response.body)
ngx.exit(response.status)
Related Topic