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!
To enable the X-Frame-Options header in Nginx, add the following line in your Nginx web server default configuration file /etc/nginx/sites-enabled/example. conf: add_header X-Frame-Options "SAMEORIGIN"; Next, restart the Nginx service to apply the changes.
The HTTP headers in NGINX are split in two parts: the input request headers (headers_in structure) and the output request headers (headers_out structure). There is no such an entity as a response, all the data is stored in the same single request structure.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With