How to Set Request Headers Conditionally in NGINX


set nginx request headers conditionally

Sometimes, you may need to set request headers with specific values, based on certain conditions so you can process them further downstream. NGINX allows you to easily do it with just a couple of lines of code. Let us take a look at how to set request headers conditionally in NGINX.

 

How to Set Request Headers Conditionally in NGINX

Here are the steps to set request headers conditionally in NGINX. We will use a simple ‘if‘ block for this purpose and also use add_header directive to set headers. However, please note, NGINX blog warns against the use of If in your NGINX config.

 

1. Open NGINX config file

Open NGINX config file in a text editor.

You will find it at one of the following locations, depending on the type of installation


/etc/nginx/conf.d/default.conf
/etc/nginx/sites-enabled/default
/etc/nginx/nginx.conf

$ sudo vim /etc/nginx/nginx.conf

 

2. Set Request Headers Conditionally

Add the following lines in your NGINX config file, depending on your requirement.

If you want to set header (e.g ‘X-Header’) for all requests on your server based on a condition variable $cond, you can add the following lines,

if ($cond) { add_header X-Header 1; }

 

The above code will set header ‘X-Header’ to value 1.

 

Here’s how to use it in a server block


server {
if ($cond) { add_header X-Header 1; }
}

 

If you want to use it in a specific location block


location /specific-url-or-directory {
if ($cond) { add_header X-Header 1; }
}

 

However, please note, if you use 2 If conditions in the same location block, only the second one will be applied. Look at the following code


location /specific-url-or-directory {
if ($cond) { add_header X-Header 1; }
if ($cond) { add_header X-Second 2; }
}

In the above code, only ‘X-Second’ will be present in request headers and not ‘X-Header’. So be careful how you use if condition in location block.

 

3. Reload NGINX web server

Test the config file to ensure there are no errors.

$ sudo nginx -t

 

If you get no error message, reload NGINX server to apply changes.

$ sudo service nginx reload

 

That’s it! Now NGINX will automatically set request headers based on specific conditions.

 

 

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!