Mastering Nginx

(Ron) #1

NGINX for the Developer


[ 170 ]

The sub module


The sub module works as a filter to replace (substitute) one text for another. It is not


compiled by default, so if you want to make use of this feature, you must enable it at
configure time by adding --with-http_sub_module.


It is fairly easy to work with. You use the sub_filter directive to specify a string


to be replaced and its replacement, and the filter makes a case-insensitive match for


your string, and substitutes in the replacement:


location / {

sub_filter </head> '<meta name="frontend" content="web3"></head>';

}

In the preceding example, we added a new meta tag to the header of the page as it


passed through NGINX.


It's also possible to make the match more than once. To do this, you set the sub_


filter_once directive to off. This can be useful to replace all relative links in a
page with absolute ones, for example:


location / {

sub_filter_once off;

sub_filter '<img src="img/' '<img src="/img/';

}

If there are any spaces or embedded quotes in the string to be matched, they must


be enclosed in quotes in order for NGINX to recognize them as the first parameter.


NGINX will automatically use the sub_filter directive on any HTML file. If you


want to use substitution on other types of files, such as JavaScript or CSS, just add
the corresponding MIME type to the sub_filter_types directive.


location / {

sub_filter_types text/css;

sub_filter url(img/ 'url(/img/';

}
Free download pdf