How to Set Custom HTTP Header With NGINX


set custom header with nginx

Sometimes, you may need to set custom HTTP header for your website, for the purpose of testing and troubleshooting. Here’s how to set custom HTTP header with NGINX.

 

How to Set Custom HTTP Header With NGINX

Here are the steps to set custom HTTP header with NGINX. You will need to compile NGINX with NginxHttpHeadersModule module for this purpose.

 

1. Open NGINX config file

Open NGINX config file in a text editor. You will typically find it at /etc/nginx/nginx.conf.


$ sudo vim /etc/nginx/nginx.conf

 

2. Add custom header

You can easily add custom header with the add_header directive.

Syntax :


add_header name value

Example:


add_header Strict-Transport-Security 157680000

 

You can use add_header directive in server, http or location block. Here are a few examples you can use as per your requirement.

 

Add custom header to all requests


location / {
add_header Strict-Transport-Security 157680000
}

 

Add custom header to a single file


location ~* (filename.pdf) {
add_header Strict-Transport-Security 157680000
}

Add Custom Headers to Multiple Files

If you want to add custom header to multiple files, based on their extensions


location ~* (.*\.pdf) {
add_header Strict-Transport-Security 157680000
}

location ~* \.(xml|js|jpg|png|css|html|otf|eot|svg|ttf)$ {
add_header Strict-Transport-Security 157680000;
}

If you want to add custom header for all .jpg files in a directory


location ~* /uploads/(.+\.jpg)$ {
add_header Strict-Transport-Security 157680000
}

 

3. Reload NGINX web server

Reload NGINX server to apply changes.

$ sudo service nginx reload

 

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!