本文主要讲 如何全局替换站点指定字符串, 如果制作 docker 容器镜像, 如何使用 dockerfile 制作镜像, nginx 含插件编译.
复制代码
前言
前段时间某个场景需要将我们产品中的一些文字替换成另外的一些文字, 比如原来全站 http 改为 https(或者将 http:// 改为 //); 比如 CDN 节点地址替换; 比如原来是 AAA 产品, 现在需要改为 BBB 产品; 比如原来网站名叫 CCC, 现在改为 DDD 等. 类似的需求, 如果一个个改, 会耗费不少时间, 而且难免会遗漏. 于是, 临时解决方案: 使用 nginx 的
ngx_http_substitutions_filter_module
模块进行全局替换.
可能有人说, 这样替换性能不是有损耗吗? 我觉得可以限定 http 返回头 (application/xml
application/javascript
text/CSS text/xml), 对于图片啊, 文件啊啥的不替换; 其次, 也可以提高 nginx 在集群中的副本数量.
认识 nginx 内容替换模块
ngx_http_substitutions_filter_module 是一个可替换内容的 nginx 插件,
可支持:
中英文替换
正则替换
支持多种替换逻辑
具体替换逻辑及使用如下如下:
subs_filter source_str destination_str [参数]
g(default): 全部替换
i: 不许分大小写替换.
o: 只替换一次
r: 正则表达式
作用域:
- http
- server
- location
支持过滤 mine 内容类型:
subs_filter_types mime-type [mime-types]
github 地址 https://github.com/yaoweibin/ngx_http_substitutions_filter_module/
说明文档 http://httpd.apache.org/docs/trunk/mod/mod_substitute.html
编译
本文均使用 docker 环境下编译, 非 docker 环境, 只需忽略 docker 基础镜像部分即可.
使用 centos 基础镜像
docker run --name subs_filter_ng -i -t -p 80:80 centos:latest /bin/bash
复制代码
下载所需组件
- yum -y install wget
- yum -y install unzip
- yum -y install gcc-c++
- yum -y install gcc automake autoconf libtool make
复制代码
下载所需文件
- cd ~
- wget http://nginx.org/download/nginx-1.8.0.tar.gz
- tar zxvf nginx-1.8.0.tar.gz
- wget http://www.zlib.net/zlib-1.2.11.tar.gz
- tar zxvf zlib-1.2.11.tar.gz
- wget https://ftp.pcre.org/pub/pcre/pcre-8.37.tar.gz
- tar zxvf pcre-8.37.tar.gz
- wget https://www.openssl.org/source/openssl-1.0.1q.tar.gz
- tar zxvf openssl-1.0.1q.tar.gz
- wget -O ngx_http_substitutions_filter_module-master.zip https://github.com/yaoweibin/ngx_http_substitutions_filter_module/archive/master.zip
- unzip ngx_http_substitutions_filter_module-master.zip
复制代码
编译
- cd /root/nginx-1.8.0
- ./configure --sbin-path=/root/nginx-1.8.0/nginx --conf-path=/root/nginx-1.8.0/nginx.conf --pid-path=/root/nginx-1.8.0/nginx.pid --with-http_ssl_module --with-pcre=/root/pcre-8.37 --with-zlib=/root/zlib-1.2.11 --with-openssl=/root/openssl-1.0.1q --with-http_stub_status_module --add-module=/root/ngx_http_substitutions_filter_module-master/ --prefix=/root/nginx-1.8.0
- make
- make install
复制代码
配置
修改 /root/nginx-1.8.0/nginx.conf 文件.
可以放到 server 里, 也可以放入 http,location.
- subs_filter_types application/xml application/javascript text/css text/xml;
- subs_filter 'http' 'https';
复制代码
记得把 user root; 注释去掉
运行
./nginx -c /root/nginx-1.8.0/nginx.conf
复制代码
打包成镜像
docker commit -m "nginx" b668 nginx/subs_filter_nginx:v1
复制代码
其中 b668 为容器 id
dockerfile
这里可以将上述脚本编写为一个 dockerfile 文件, 方便以后使用.
总结
这样一个可以替换内容的 nginx 镜像就诞生了, 希望通过本文的例子能帮助大家理解 nginx 编译过程 (毕竟 nginx 不像其他 apache 啥的增加模块只需要引入文件即可, nginx 增加模块都需要重新编译).
来源: https://juejin.im/post/5b73bcacf265da28260cd1c9