How can I add header conditionally in nginx configuration?
I used lua nginx module to solve a similar problem:
localtion / {
header_filter_by_lua_block {
ngx.header["X-TEST-0"] = "always-0";
# example of conditional header
if ngx.req.get_method() == ngx.HTTP_POST {
ngx.header["X-TEST-1"] = "only if POST request";
}
ngx.header["X-TEST-2"] = "always-2";
}
}
https://github.com/openresty/lua-nginx-module#header_filter_by_lua_block ```
This is simple if you think differently and use a map.
map $variable $headervalue {
1 only-true;
default '';
}
# ...later...
location / {
add_header X-TEST-1 $headervalue;
}
If $variable is 1, $headervalue will be set and hence the header will be added. By default $headervalue will be empty and the header will not be added.
This is efficient because Nginx only evaluates the map when it's needed (when it gets to a point where $headervalue is referenced).
See similar: https://serverfault.com/questions/598085/nginx-add-header-conditional-on-an-upstream-http-variable