add_before_body
The `add_before_body` directive allows you to insert additional content before the HTTP response body in NGINX.
Description
The add_before_body directive is used within the NGINX HTTP core module to append specific content before the body of the response is sent to the client. This can be particularly useful for injecting scripts, notes, or other markup directly into the response payload without modifying the application or backend server. The inserted content can be defined as a string literal that is outputted as part of the HTTP response during the request processing phase.
The directive can be specified in contexts such as http, server, and location, enabling fine-grained control over where the content is inserted. The argument to this directive is a single string value that denotes the content to be added. Once configured, add_before_body processes the request at the output phase, ensuring that the specified content precedes the original response body.
Because this modifies the response structure, it's important to ensure that the inserted content does not interfere with the content type or structure of the response. Careful consideration should be given to the content being added to maintain valid HTTP response formatting.
Config Example
http {
server {
location /example {
add_before_body '';
}
}
}Ensure that the inserted content is valid and does not break the structure of the main response body.
Using large amounts of content may affect response sizes and performance.
Avoid adding content that alters content types unintentionally.