sub_filter_once

The `sub_filter_once` directive controls whether a substitution is applied only once per response, or every time the specified substring is found.

Syntaxsub_filter_once on | off;
Defaultoff
Contexthttp, server, location
Argumentsflag

Description

The sub_filter_once directive is used within the NGINX http, server, or location context to dictate the behavior of substring replacements made by the sub_filter directive. When set to on, the substitution will only replace the first occurrence of the designated string in the response body. Conversely, if set to off, sub_filter will process all instances of the substring, altering them in the compiled output. This is particularly useful for managing instances where multiple identical strings are present, and a singular replacement suffices without modifying every instance—thus avoiding unintended alterations to the response's context.

This directive can accept either a Boolean value ('on' or 'off'). By default, it is typically set to off, meaning that multiple substitutions are allowed unless specified otherwise. Implementing sub_filter_once requires enabling the sub module within NGINX, which is critical for this directive to function effectively. An additional consideration is that sub_filter must also be configured to ensure the specific substrings to substitute are identified clearly before applying the single or multiple replacements based on the sub_filter_once setting.

Config Example

sub_filter 'old_text' 'new_text';
sub_filter_once on;

Ensure the sub_filter directive is used alongside sub_filter_once; it is ineffective in isolation.

Be aware that the order of directives may affect the overall output, particularly in complex response bodies.

Using sub_filter_once in high traffic scenarios can lead to performance implications due to the additional checks for substitution occurrences.

← Back to all directives