sub_filter

The sub_filter directive is used to modify the response body by substituting specific strings with others.

Syntaxsub_filter "search" "replace";
Defaultnone
Contexthttp, server, location
Arguments2

Description

The sub_filter directive allows you to dynamically replace strings in the response body of HTTP traffic served by NGINX. This can be particularly useful for modifying content on-the-fly, such as adapting links or text based on the environment or for localization purposes. The directive accepts two parameters: the first is the string to search for in the response body, and the second is the string to replace it with. Each time NGINX processes a response, it scans the output for occurrences of the specified search string and replaces them with the specified replacement string before sending the response to the client.

It is important to note that the sub_filter directive operates only if the response body size is less than the configured buffer size and when the response code is in the 200-299 range. Additionally, the directive supports regular expressions for matching strings if the 'sub_filter_types' directive is properly configured. This can help in implementing more complex substitutions, but care must be taken to ensure that regex patterns are properly escaped and crafted to avoid unintended matches or performance degradation due to excessive backtracking in complex patterns.

Config Example

location /example {
    sub_filter "example.com" "example.org";
    sub_filter_once off;
}

Make sure the 'sub_filter_types' directive includes the MIME types of the responses where substitutions are needed, or the directive may not function as expected.

Substitution only occurs if the Content-Type of the response matches those specified in 'sub_filter_types' and the response status is in the 200-299 range.

If using regular expressions, ensure the patterns are correctly formatted to avoid invalid matches.

← Back to all directives