Friday, 27 December 2019

NGINX: Add response headers


Using ‘add_header’ directive we can add response headers.

Syntax:    add_header name value [always];
Default:   
Context:    http, server, location, if in location

By default ‘add_header’ directive add the headers only if the response code equals 200, 201, 204, 206, 301, 302, 303, 304, 307, or 308.

If you want to set the headers irrespective of response codes, then use the parameter ‘always’.

Example
location = /about{
  add_header url "/about";
  add_header version "1.23.4";
           
  return 200 "Hello Welcome to NGINX";
}

nginx.conf
events {
}

http {
    include mime.types;

    # Buffer size for POST submissions
    client_body_buffer_size 10K;
    client_max_body_size 4m;

    # Buffer size for Headers
    client_header_buffer_size 1k;

    client_body_timeout 60s;

    client_header_timeout 60s;

    keepalive_timeout 75s;

    send_timeout 60s;

    server {
        listen 9090;

        server_name localhost;

        location = /about{
            add_header url "/about";
            add_header version "1.23.4";
            
            return 200 "Hello Welcome to NGINX";
        }

        location = /not_found{
            return 404 "File can't be found";
        }
    }
}


Validate and reload the configuration
$sudo nginx -t
Password:
nginx: the configuration file /usr/local/etc/nginx/nginx.conf syntax is ok
nginx: configuration file /usr/local/etc/nginx/nginx.conf test is successful
$
$sudo nginx -s reload


When I hit the url ‘localhost:9090/about’, I can see the response headers.
$CURL -I localhost:9090/about
HTTP/1.1 200 OK
Server: nginx/1.17.3
Date: Wed, 16 Oct 2019 14:45:37 GMT
Content-Type: text/plain
Content-Length: 22
Connection: keep-alive
url: /about
version: 1.23.4


Previous                                                    Next                                                    Home

No comments:

Post a Comment