yazaki
yazaki

Reputation: 1632

How can I add header conditionally in nginx configuration?

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!

Upvotes: 40

Views: 36122

Answers (3)

Salem
Salem

Reputation: 784

I solve it this way, I wanted to print a specified country symbol first, I map the geo if certain IP's in the server blocks

geo $CNTRY {
    default '';
    192.104.49.0/24 ML;
    192.104.46.0/24 ML;
    192.104.47.0/24 ML;
}

Then I simply add it to server block, (anywhere doesn't matter)

add_header x-CNTRY $CNTRY;

Upvotes: 0

Ed Randall
Ed Randall

Reputation: 7610

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

Upvotes: 16

korya
korya

Reputation: 2026

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

Upvotes: 6

Related Questions