nginx是一款轻量级高性能服务器软件,虽然轻量,但功能非常强大,可用于提供web服务、反向代理、负载均衡、缓存服务、甚至可以通过添加一些模块搭建rtmp流媒体服务。最近碰到一个客户需求,需要用到nginx网页内容替换模块,贴出来跟大家交流,如有不足之处请指出。
ngx_http_sub_module模块是一个过滤器,它修改网站响应内容中的字符串。这个模块已经内置在nginx中,但是默认未安装,需要安装需要加上配置参数:--with-http_sub_module 如果已经安装nginx,只需要再添加这个模块就可以了。
安装替换
nginx官网下载安装包:http://nginx.org/en/download.html
# wget http://nginx.org/download/nginx-1.11.5.tar.gz
# tar -zxvf nginx-1.11.5.tar.gz
# cd nginx-1.11.5
# ./configure --with-http_stub_status_module --with-http_sub_module && make && make install
常用指令
sub_filter指令
sub_filter string(原字符串) replacement(用于替换的字符串);
用于设置需要使用说明字符串替换说明字符串.string是要被替换的字符串,replacement是新的字符串,它里面可以带变量。
sub_filter_last_modified指令
sub_filter_last_modified on | off;
用于设置网页内替换后是否修改 可在nginx.conf的 http, server, location三个位置配置使 用,默认值是off;
sub_filter_once指令
sub_filter_once on | off;
用于设置字符串替换次数,默认只替换一次。如果是on,默认只替换第一次匹配到的到字 符,如果是off,那么所有匹配到的字符都会被替换;
sub_filter_types指令
sub_filter_types *
用于指定需要被替换的mime类型,默认为“text/html”,如果制定为*,那么所有的;
说明:以上指令可在nginx.conf的http, server, location三个位置配置使用;
反向代理动态替换网页内容实例参考
server {
listen 80;
server_name mikecrm.xianzhixiong.com;
# 上传文件大小限制
client_max_body_size 20m;
# 设置为on表示启动高效传输文件的模式
sendfile on;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
#access_log logs/host.access.log main;
location / {
#root html;
#index index.html index.htm;
proxy_pass http://mikecrm.com;
proxy_set_header host mikecrm.com;
proxy_set_header referer http://mikecrm.com;
proxy_set_header x-real-ip $remote_addr;
proxy_set_header x-forwarded-for $proxy_add_x_forwarded_for;
proxy_set_header x-forwarded-proto $scheme;
#proxy_request_buffering off;
proxy_set_header accept-encoding "";
sub_filter_types *;
sub_filter_once off;
#sub_filter_last_modified on;
sub_filter 'cdnq2.mikecrm.com' 'mikecrm.xianzhixiong.com';
sub_filter 'cdnq3.mikecrm.com' 'mikecrm.xianzhixiong.com';
sub_filter 'https://cdnq2plt.mikecrm.com' 'http://mikecrm.xianzhixiong.com';
sub_filter 'https://cdnq3plt.mikecrm.com' 'http://mikecrm.xianzhixiong.com';
sub_filter 'http://dlcn.mikecrm.com' '';
sub_filter 'http://mikecrm.com' '';
sub_filter 'https://mikecrm.com' '';
sub_filter 'www.mikecrm.com' 'mikecrm.xianzhixiong.com';
#sub_filter '.mikecrm.com' 'mikecrm.xianzhixiong.com';
#sub_filter 'mikecrm.com' 'mikecrm.xianzhixiong.com';
}
#location ~ \.php$ {
# proxy_pass https://real.mikecrm.com;
#}
#location ~ /plt.js$ {
# proxy_pass https://cdnq3plt.mikecrm.com;
#}
}参数解释
注意只有在新版本nginx中才支持多sub_filter.
proxy_set_header accept-encoding "";
设置这个得原因是:告诉后端不要进行gzip压缩. 如果是gzip压缩流, 那么我们就没法进行替换了.
sub_filter_types *;
对所有请求响应类型都做sub_filter指定的替换.
sub_filter_once off;
sub_filter会执行多次而不是一次. 效果类似于java中的string.replaceall而不是replace.
sub_filter 'str1' 'str2';
替换字符串,str1是搜索的字符串,str2是最终被替换成的字符串
总结
到此这篇关于nginx反向代理和内容替换模块实现网页内容动态替换功能的文章就介绍到这了,更多相关nginx反向代理替换网页字符串内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论