more_set_headers
The `more_set_headers` directive is used to set or modify HTTP response headers in NGINX.
Description
The more_set_headers directive from the NGINX Headers More module allows users to set or modify HTTP headers in the response sent to clients. It provides greater flexibility than the built-in NGINX add_header directive by allowing the resetting of headers, as well as the ability to clear existing headers. The directive supports multiple parameters, including specific HTTP status codes and MIME types, which can determine when the headers should be applied.
A key feature of more_set_headers is that it can conditionally set headers based on the response status codes (e.g., -s 404) or the content type (e.g., -t 'text/html'). This means users can target their header modifications based on the nature of the response, such as adding a specific header only for certain error responses or content types. The directive can accept multiple header definitions within a single statement, streamlining the configuration process.
When using more_set_headers, it’s also possible to create location or server-specific configurations, allowing for a fine-tuned approach to header management across different parts of an application. This can be particularly useful for API responses, static file delivery, or when fine control over header content is required for security, caching, or browser compatibility reasons.
Config Example
location /api {
more_set_headers 'X-Content-Type-Options: nosniff';
more_set_headers -s 404 'X-Error: Not Found';
more_set_headers -t 'application/json' 'Content-Type: application/json';
}Ensure that the headers being set do not conflict with existing headers; conflicts can lead to unexpected behavior.
Remember that header modifications are not applied if the response has already been sent; place this directive before the point where the response is finalized.
Be cautious when using the -s and -t options as incorrect usage can result in headers not being set when expected.