how to modify header in nginx

How to Modify Response Header in NGINX

Sometimes you may need to change response header or override response header for some of your location blocks in NGINX. In this article, we will look at how to modify response header in NGINX.


How to Modify Response Header in NGINX

Here are the steps to modify response header in NGINX.


1. Open NGINX configuration file

Open terminal and run the following command to open NGINX configuration file.

$ sudo vi /etc/nginx/nginx.conf


2. Add response headers

There are two ways to change response headers in NGINX. We will look at both of them.


Using add_header

You can use add_header directive to set response headers for your location blocks. Here is an example where we use add_header to set server header in location block for /.

location / {
   ...
   add_header Server "abc"
   ...
}

Basically, you need to mention the header name and value after add_header directive. The above code will override the Server name present in your server’s response headers. However, it works only on direct responses which do not use proxy_pass directive. If you use proxy_pass directive in your location block, then you will need to use more_set_headers as shown below.


Using more_set_headers

The NGINX module more_set_headers offers more control over headers. However, it is not installed by default. You will have to compile more_set_headers with NGINX during installation. Here are the commands to do so.

$ sudo wget 'http://nginx.org/download/nginx-1.17.8.tar.gz'
$ sudo tar -xzvf nginx-1.17.8.tar.gz
$ cd nginx-1.17.8/

# Here we assume you would install you nginx under /opt/nginx/.
$ ./configure --prefix=/opt/nginx --add-module=/path/to/headers-more-nginx-module

$ make
$ make install

Once you have installed more_set_headers module, you can use it in location block as shown below.

location / {
    ...
    more_set_headers "Server: abc";
    ...
}

In above case, the header will be updated even if the request is passed to other servers using proxy_pass directive. It will replace headers for any status code and any response type. It will also override existing header value.


3. Restart NGINX server

Test NGINX configuration for error

$ sudo nginx -t

If you don’t see any error message, restart NGINX server to apply changes.

$ sudo service nginx restart

In this article, we have learnt two ways to set response headers in NGINX – using add_headers directive and more_set_headers directive. You can use them to modify response headers as per your requirement.

Also read:

NGINX Location Block Precedence
How to Fix Errno 13 Permission Denied in Apache
How to Define & Use Variable in Apache
NGINX: Protect Static Files with Authentication
How to Setup Apache Virtual Host in Windows

Leave a Reply

Your email address will not be published. Required fields are marked *