add_header

The `add_header` directive sets HTTP response headers in NGINX.

Syntaxadd_header name value [always];
Defaultnone
Contexthttp, server, location, if in location
Arguments2-3

Description

The add_header directive allows for the inclusion of specific HTTP headers in the responses sent by NGINX. This can be particularly useful for configuration parameters such as security policies (Strict-Transport-Security, Content-Security-Policy) or for managing caching behaviors (Cache-Control, Expires). When specified, it sets the headers for the defined context (http, server, or location).

Multiple headers can be defined with multiple add_header directives, and if the header already exists, its value can be altered when using this directive. A key behavior to note is that add_header does not overwrite existing headers unless the always parameter is used, which ensures that the added headers are included even when the response code indicates an error (like 4xx or 5xx responses). This allows managing header visibility regardless of the underlying application logic response.

Config Example

server {
    listen 80;
    server_name example.com;
    add_header X-Frame-Options "DENY";
    location / {
        add_header Content-Security-Policy "default-src 'self'";
    }
}

If you forget to specify 'always', headers might not be included in error responses (4xx/5xx).

Headers added in a nested context (like location) will override headers defined in a parent context (like server).

Be cautious with duplicate headers — only the last defined value will take effect when redefined.

← Back to all directives