ngx_http_sub_module

Replace one string with another in response bodies

compiled inBSD-2-Clausesource docs

Overview

ngx_http_sub_module is a filter that modifies a response by replacing one specified string with another. The string to replace is matched ignoring case, and both the search string (1.9.4) and the replacement may contain variables.

Several sub_filter directives can be given at the same level since 1.9.4, and they are inherited from the previous level only when the current level defines none. By default each string is replaced once and only text/html responses are processed; sub_filter_types extends this to other MIME types and sub_filter_last_modified keeps the Last-Modified header that is otherwise dropped. For regular expressions and more flexible multiple substitutions, the third-party module at /modules/subs-filter/ builds on the same idea.

It is an official nginx module that upstream does not build by default; it needs the --with-http_sub_module configure parameter. A typical use is rewriting absolute links or hostnames in HTML coming from a proxied backend.

Key directives

sub_filterSets a string to replace and its replacement; case-insensitive match, variables allowed, repeatable since 1.9.4.
sub_filter_onceWhether to look for each string once or repeatedly, default on.
sub_filter_typesAdditional MIME types to process besides text/html, default text/html; "*" matches any type (0.8.29).
sub_filter_last_modifiedPreserves the Last-Modified header from the original response to aid caching (1.5.1), default off.

Example

nginx.conf
location / { proxy_pass http://127.0.0.1:8080; # rewrite backend links to the public host sub_filter '<a href="http://127.0.0.1:8080/' '<a href="https://$host/'; sub_filter '<img src="http://127.0.0.1:8080/' '<img src="https://$host/'; sub_filter_once off; sub_filter_types text/css application/javascript; }

Availability

Compiled into every n.wtf nginx binary. Install nginx-extras and the directives above work out of the box, no load_module line needed.