Nginx 服务提供修改返回客户端内容的功能;也就是,当Nginx服务返回给浏览器内容时,可以修改返回的内容。
一、with-http_sub_module模块
1.1、sub_filter string replacement;
Default: —
Context: http, server, location
允许使用一些其他的文本替换nginx应答内容中的一些文本。
匹配不区分大小写,替换的文本可以包含变量。
当且仅当sub_filter在当前级别上没有定义指令时,这些指令将从上一级继承。
1.2、sub_filter_once on | off;
Default: on;
Context:http, server, location
是否查找每个字符串以替换一次或重复。
1.3、sub_filter_types mime-type …;
Default:sub_filter_types text/html;
Context: http, server, location
指定sub_filter指令将检查那些内容类型,默认为text/html
二、ngx_http_substitutions_filter_module 增强功能
模块substitutions4nginx
支持多次替换
支持正则替换
支持中文替换
不能使用到 if 判断模块内
2.1、subs_filter_types
语法: subs_filter_types mime-type [mime-types]
默认: subs_filter_types text/html
适用: http, server, location
用来指定替换文件类型的 默认仅仅替换text/html类型的文件。
2.2、subs_filter
语法: subs_filter source_str destination_str [gior]
默认: none
适用: http,server,location
用来替换文本的,可以使用正则
g:替换匹配项。
i:区分大小写的匹配。
o:只匹配发现的第一个。
r:正则匹配。
2.3、subs_filter_once on | off;
Default:subs_filter_once on;
Context: http, server, location
on:只替换第一个匹配项
off:允许搜索并替换所有匹配行
三、使用示例
3.1、使用示例
location / {
subs_filter_types text/html text/css text/xml;
subs_filter st(\d*).example.com $1.example.com ir;
subs_filter a.example.com s.example.com;
subs_filter http://$host https://$host;
3.2、使用案例
1、将页面中的http链接全部替换为https
location / {
subs_filter http:// https:// gr;
2、域名替换
location / {
subs_filter https://domain1.net/([^"\']*?)\.(jpg|png|js|css|jpeg|bmp) https://domain2.com/$1.$2 igr;
3、在使用正则模式时,不能使用nginx内置变量,比如:$host,否则会出现如下报错:
nginx: [emerg] match part cannot contain variable during regex mode in ***