Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add header conditionally in nginx configuration?

Tags:

nginx

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...

  1. How can I add header conditionally?

  2. Why does nginx add only X-TEST-1 with my first example above?

Thanks in advance!

like image 609
yazaki Avatar asked Apr 06 '15 08:04

yazaki


People also ask

Where do I put headers in nginx?

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.

What is header in nginx?

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.


1 Answers

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

like image 88
Ed Randall Avatar answered Sep 25 '22 15:09

Ed Randall