nginx 自從 1.9.11 以后就支持動(dòng)態(tài)加載模塊了, 不需要重新編譯 nginx, 只需要將模塊編譯為 so 然后在 nginx 的配置文件中加載就行。
nginx 版本可用 nginx -v 查看
root@aliyun:/# nginx -v nginx version: nginx/1.17.9
可以得知目前 docker 容器內(nèi)的 nginx 版本為 1.17.9, 下載 nginx 源碼以及模塊源碼并解壓
wget https://github.com/nginx/nginx/archive/release-1.17.9.tar.gz tar -xvf release-1.17.9.tar.gz
git clone https://github.com/yaoweibin/ngx_http_substitutions_filter_module.git
Nginx 模塊源碼中存在著 config 腳本文件, 靜態(tài)模塊和動(dòng)態(tài)模塊的配置文件時(shí)不同的。新格式的 config 腳本是同時(shí)兼容動(dòng)態(tài)模塊和靜態(tài)模塊的, 模塊的 config腳本還是舊的格式, 則需要根據(jù)文檔去轉(zhuǎn)換。
有些模塊是無法被配置為動(dòng)態(tài)模塊的。
新式配置腳本樣例
ngx_addon_name=ngx_http_hello_world_module if test -n "$ngx_module_link"; then ngx_module_type=HTTP ngx_module_name=ngx_http_hello_world_module ngx_module_srcs="$ngx_addon_dir/ngx_http_hello_world_module.c" . auto/module else HTTP_MODULES="$HTTP_MODULES ngx_http_hello_world_module" NGX_ADDON_SRCS="$NGX_ADDON_SRCS $ngx_addon_dir/ngx_http_hello_world_module.c" fi
舊式配置腳本樣例
ngx_addon_name=ngx_http_response_module HTTP_MODULES="$HTTP_MODULES ngx_http_response_module" NGX_ADDON_SRCS="$NGX_ADDON_SRCS $ngx_addon_dir/ngx_http_response_module.c"
轉(zhuǎn)換的方法見: https://www.nginx.com/resources/wiki/extending/converting/
本文提及的 ngx_http_substitutions_filter_module 使用的新式腳本, 因此可以直接被編譯為動(dòng)態(tài)模塊無需配置。
先安裝編譯時(shí)依賴的庫(需要安裝的庫可能不止這些, 跟著報(bào)錯(cuò)找的)
sudo apt install make gcc zlib1g-dev libpcre3-dev libssl-dev
由于新版 nginx 目錄結(jié)構(gòu)的改版, 源碼的目錄結(jié)構(gòu)和舊版本的不太一樣:
configure 腳本從根目錄移到了 auto 目錄下
cd 進(jìn) nginx 源碼目錄后使用 --with-compat 和 --add-dynamic-module 參數(shù)來配置編譯環(huán)境
./auto/configure --with-compat --add-dynamic-module=../ngx_http_substitutions_filter_module make modules
編譯出來的模塊在 objs\ngx_http_subs_filter_module.so
根據(jù)官方文檔來講, 只需要添加兩個(gè)參數(shù)就可以編譯動(dòng)態(tài)模塊了。但是, 實(shí)際環(huán)境中 nginx 的編譯參數(shù)可能是很復(fù)雜的, 如果發(fā)現(xiàn)編譯出來的模塊無法正常加載, 可以考慮用 nginx -V 查看編譯 nginx 時(shí)使用的參數(shù), 將參數(shù)加入 configure 命令后再次嘗試編譯加載模塊
我使用的 nginx docker 鏡像為 nginx 官方的鏡像, 模塊被存放在 /usr/lib/nginx/modules 下, 將模塊掛載入 container 后, 修改 nginx 配置文件 /etc/nginx/nginx.conf, 加入
load_module modules/ngx_http_subs_filter_module.so;
重載容器中的 nginx 配置即可使用新模塊
修改完配置文件后可以在 maps 中看到 so 已被加載