subs-filter

Regex and string substitution on response bodies

dynamic moduleBSD-2-Clausesource

Overview

ngx_http_substitutions_filter_module rewrites response bodies on the fly, replacing text by fixed string or regular expression. It is similar to Apache mod_substitute and scans output buffers line by line.

Unlike the stock sub_filter module, it supports regular expressions and multiple substitution rules in one location. Typical uses are fixing absolute URLs behind a reverse proxy, switching http links to https, and masking hostnames in proxied content.

The module is written by Weibin Yao. Responses are filtered only for the MIME types listed in subs_filter_types, text/html by default.

Key directives

subs_filterReplaces a source string or regex with a destination string, with flags for global (g), case-insensitive (i), first-match-only (o), and regex (r) matching.
Multiple rules per locationSeveral subs_filter directives can apply in the same location, and each line of the response is checked against all of them.
subs_filter_typesLists the MIME types to filter, defaulting to text/html; add text/css, text/xml, or others as needed.
subs_filter_bypassSkips filtering when a given variable is non-empty and not 0, so substitution can be toggled per request.
Variable supportBoth match and replacement strings may contain nginx variables such as $host, though variables in the match side disable some optimizations.

Example

nginx.conf
load_module modules/ngx_http_subs_filter_module.so; http { server { location / { proxy_pass http://127.0.0.1:8080; subs_filter_types text/html text/css; subs_filter http://internal.example.com https://www.example.com gi; subs_filter foo bar gi; } } }

Availability

Ships as a dynamic module in libnginx-mod-http-subs-filter, installed automatically with nginx-extras. The package drops a load_module config into /etc/nginx/modules-enabled/, so it loads on start.