nginx add header conditional on an upstream_http_ variable
Solution 1:
This doesn't work because the if is evaluated before the request is passed to the backend, so the $upstream_http_ variables don't have any values yet. add_header with an empty value is ignored, so you can use a map to conditionally add the header like so:
map $upstream_http_strict_transport_security $sts {
'' max-age=15552000;
}
server {
location / {
add_header Strict-Transport-Security $sts;
}
}
Solution 2:
That's because if
is executed before proxy take place and at this moment there is no variable $upstream_http_strict_transport_security
.
You could use header_filter_by_lua
directive from Lua module. E.g.
header_filter_by_lua 'if not ngx.header["X-Test"] then ngx.header["X-Test"] = "blah" end';