subs_filter

The `subs_filter` directive performs string substitutions within the response body of HTTP requests.

Syntaxsubs_filter source_str destination_str [gior];
Defaultnone
Contexthttp, server, location
Arguments2+

Description

The subs_filter directive in the NGINX String Substitutions Module allows users to specify required substitutions directly within the response body before it is sent to the client. It supports both fixed string and regular expression replacements. The basic usage involves defining a source string and a destination string, where the source represents the text to be matched and replaced in the response. Additionally, the directive accepts flags that modify its behavior; for example, 'g' indicates to replace all occurrences of the source string, 'i' makes the match case-insensitive, and 'o' restricts the substitution to the first occurrence. The 'r' flag specifies that the source is a regular expression instead of a fixed string, though it has restrictive variable handling compared to fixed string mode.

Users can invoke multiple subs_filter directives within the same context, enabling complex substitution scenarios. It is important to note that subs_filter works with non-compressed text responses, as it cannot process compressed output. To ensure the correct operation, the appropriate content types must be specified using the subs_filter_types directive. Overall, this directive gives considerable flexibility in modifying HTTP responses, akin to features found in the Apache mod_substitute module.

Config Example

location / {
    subs_filter_types text/html text/css;
    subs_filter st(\d*).example.com $1.example.com ir;
    subs_filter a.example.com s.example.com;
    subs_filter http://$host https://$host;
}

Ensure the source string in regular expressions does not contain variables, as they are only available in fixed string mode.

Substitutions will not work on compressed responses unless explicitly configured to not compress the output.

Check that appropriate MIME types are configured with subs_filter_types, or the directive will not trigger on unsupported content types.

← Back to all directives