Py学习  »  docker

随手打造一个可以替换全站字符串的nginx镜像(docker)

邵磊 • 5 年前 • 248 次点击  
阅读 18

随手打造一个可以替换全站字符串的nginx镜像(docker)

本文主要讲 如何全局替换站点指定字符串、如果制作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插件,

可支持:

  1. 中英文替换
  2. 正则替换
  3. 支持多种替换逻辑

具体替换逻辑及使用如下如下:

subs_filter source_str destination_str [参数]

  1. g(default): 全部替换
  2. i: 不许分大小写替换.
  3. o: 只替换一次
  4. r: 正则表达式

作用域:

  1. http
  2. server
  3. location

支持过滤mine内容类型: subs_filter_types mime-type [mime-types]

github地址

说明文档

编译

本文均使用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增加模块都需要重新编译)。


今天看啥 - 高品质阅读平台
本文地址:http://www.jintiankansha.me/t/ZPJHvkxt1b
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/22531
 
248 次点击