Reputation: 327
I am using the access_by_lua_block
in my nginx configuration to add/modify custom request headers (let's say ngx.req.set_header("foo", "bar")
). I am accessing these headers within the header_filter_by_lua_block
as ngx.var["http_foo"]
just before returning any response to the client.
This works fine in case of passing the request to upstream, however it doesn't work in case of redirects.
So basically,
This works (No redirect).
location /abc {
proxy_pass some_upstream;
access_by_lua_block {
ngx.req.set_header("foo", "bar")
}
header_filter_by_lua_block {
ngx.header["foo2"] = ngx.var["http_foo"] # this is correctly getting the value of "foo" header set above
}
}
This doesn't work (With Redirect)
location /abc {
access_by_lua_block {
ngx.req.set_header("foo", "bar")
}
header_filter_by_lua_block {
ngx.header["foo2"] = ngx.var["http_foo"] # this is not getting the value of "foo" header set above
}
return 301 xyz.com;
}
The access_by_lua_block is not getting executed in case of redirects only (return 301 statement). I don't understand why so? Because access_by_lua_block has a execution priority before the content phase (link)
Upvotes: 4
Views: 8034
Reputation: 15518
As far as I understand, execution of return
directive happens within the rewrite phase, and access phase doesn't executed at all in this case. You can try to change access_by_lua_block
to rewrite_by_lua_block
and see what happens.
First attempt to solve the problem gives nothing. Indeed, as lua-ngx-module documentation for rewrite_by_lua
states:
Note that this handler always runs after the standard ngx_http_rewrite_module.
What else you could try is to do the redirect inside the rewrite_by_lua_block
:
location /abc {
rewrite_by_lua_block {
ngx.req.set_header("foo", "bar")
ngx.redirect("xyz.com", 301)
}
header_filter_by_lua_block {
ngx.header["foo2"] = ngx.var["http_foo"] # this is not getting the value of "foo" header set above
}
}
Upvotes: 3