隨手打造一個能夠替換全站字符串的nginx鏡像(docker)

本文主要講 如何全局替換站點指定字符串、若是製做docker容器鏡像、如何使用dockerfile製做鏡像、nginx含插件編譯。
複製代碼

前言

前段時間某個場景須要將咱們產品中的一些文字替換成另外的一些文字,好比原來全站http改成https(或者將http://改成//);好比CDN節點地址替換;好比原來是AAA產品,如今須要改成BBB產品;好比原來網站名叫CCC,如今改成DDD等。相似的需求,若是一個個改,會耗費很多時間,並且不免會遺漏。因而,臨時解決方案:使用nginx的ngx_http_substitutions_filter_module模塊進行全局替換。javascript

可能有人說,這樣替換性能不是有損耗嗎?我以爲能夠限定http返回頭(application/xml application/javascript text/css text/xml),對於圖片啊,文件啊啥的不替換;其次,也能夠提升nginx在集羣中的副本數量。css

認識nginx內容替換模塊

ngx_http_substitutions_filter_module是一個可替換內容的nginx插件,html

可支持:

  1. 中英文替換
  2. 正則替換
  3. 支持多種替換邏輯

具體替換邏輯及使用以下以下:

subs_filter source_str destination_str [參數]java

  1. g(default): 所有替換
  2. i: 不準分大小寫替換.
  3. o: 只替換一次
  4. r: 正則表達式

做用域:

  1. http
  2. server
  3. location

支持過濾mine內容類型: subs_filter_types mime-type [mime-types]nginx

github地址c++

說明文檔git

編譯

本文均使用docker環境下編譯,非docker環境,只需忽略docker基礎鏡像部分便可。github

使用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。docker

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
複製代碼

vi不支持中文解決方案

cat << EOF > /root/.vimrc

:set encoding=utf-8

:set fileencodings=ucs-bom,utf-8,cp936

:set fileencoding=gb2312

:set termencoding=utf-8

EOF

複製代碼

打包成鏡像

docker commit -m "nginx" b668 nginx/subs_filter_nginx:v1
複製代碼

其中b668爲容器id

dockerfile

這裏能夠將上述腳本編寫爲一個dockerfile文件,方便之後使用。

總結

這樣一個能夠替換內容的nginx鏡像就誕生了,但願經過本文的例子能幫助你們理解nginx編譯過程(畢竟nginx不像其餘apache啥的增長模塊只須要引入文件便可,nginx增長模塊都須要從新編譯)。

相關文章
相關標籤/搜索