How can I add header conditionally in nginx(1.4.6 ubuntu) configuration?
At first I tried like this.
location / {
add_header X-TEST-0 always-0;
set $true 1;
if ($true) {
add_header X-TEST-1 only-true;
}
add_header X-TEST-2 always-2;
}
Although I expected my nginx set all header(X-TEST-0,1,2), it added header only X-TEST-1.
Next I tried like this.
location / {
add_header X-TEST-0 always-0;
##set $true 1;
##if ($true) {
## add_header X-TEST-1 only-true;
##}
add_header X-TEST-2 always-2;
}
My nginx added header X-TEST-1 and X-TEST-2 as I expected.
My quastions are...
How can I add header conditionally?
Why does nginx add only X-TEST-1 with my first example above?
Thanks in advance!
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
(I would write this conclusion for the people who will have the same question in the future. Thanks to @Alexey Ten for the information.)
Conclusion:
Don't use any non-rewrite directives inside if
directives. Because if
directive is essentially part of rewrite module.
We could get more details about it in official document named IfIsEvil.