How can I add header conditionally in nginx configuration?

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)