How to Add Conditional Headers in NGINX

Sometimes you may need to add headers conditionally in NGINX based on specific conditions. While it might be tempting to use if condition, it is advisable to use map function to do this. In this article, we will look at how to add conditional headers in NGINX. You can use them to set headers conditionally in NGINX.


How to Add Conditional Headers in NGINX

Here are the steps to add conditional headers in NGINX. NGINX documentation advises us not to use IF condition with detailed explanation here. So we will use map functionality in NGINX.

Let us say you want to set X-TEST-1 to true if http_host server variable is staging, else keep it blank.

In such cases open NGINX configuration file and add the following lines inside server block.

server {
...

map $http_host  $headervalue {
    "staging"        true;
    default  '';
}

...
}

As per the above code, headervalue will be set to true if server variable http_host value is staging, else it will be blank. Please note, for map function, you can only test the value of server variables such as $http_host or $host that are available throughout the configuration.

Also read : How to Install Apache Cassandra in Ubuntu


Now we can use this variable headervalue in subsequent server configuration as shown below.

#defined later after map
location / {
    ...
    add_header X-TEST-1   $headervalue;
    ...
}

In the above code, the value of X-TEST-1 variable will be set to headervalue. So it will be true if http_host is staging, else it will be blank.

Also read : How to Create Empty File in Linux

Similarly, you can update conditionally set headers using regular expressions for pattern matching. Here is an example.

map $http_host $headervalue {
    default "";
    # if $http_host contains the word staging
    "~*staging" "noindex, nofollow, nosnippet, noarchive";
}

Now you can use the headervalue set other header values.

location / {
    ...
    add_header X-Robots-Tag   $headervalue;
    ...
}

Restart NGINX Server to apply changes.

$ sudo service nginx restart
OR 
$ sudo systemctl restart nginx

That’s it. As you can see, Map is a very useful function to set headers conditionally in NGINX. In this article we have seen how you can add conditional headers in NGINX and change the way your server processes requests depending on specific conditions. It is also a great way to define custom variables that may not be available directly in the server and then use the to process requests as per your requirement.