需先确认Nginx版本≥1.9.11、含dynamic和--with-compat支持,再下载同版本源码,用--add-dynamic-module和--with-compat配置后执行make modules生成.so文件,复制至--modules-path目录并以绝对路径在nginx.conf main块中用load_module加载。

要为已安装的 Nginx 编译独立的动态模块(.so 文件),核心是“复用原版源码 + 匹配版本 + 仅编译模块”,不重新构建主程序。前提是当前 Nginx 版本 ≥1.9.11,且原始编译时启用了动态模块兼容性(通常官方包默认支持,自编译需含 --with-compat)。
确认基础环境是否就绪
执行 nginx -V,检查输出中是否包含:
- dynamic(表示支持动态模块)
- --with-compat(关键!缺失则无法加载第三方动态模块)
-
--modules-path=...(记录模块存放路径,如
/usr/lib/nginx/modules)
获取匹配的 Nginx 源码
必须与运行中的 Nginx 版本完全一致(如 nginx version: nginx/1.24.0,就要下载 nginx-1.24.0.tar.gz)。来源优先选:
– 官网 nginx.org/download/
– 或通过 nginx -V 中的 built by 信息判断是否为发行版定制包,必要时从对应仓库获取源码包
编译指定动态模块
以 echo-nginx-module 为例,流程如下:
- 解压 Nginx 源码,进入目录:
cd nginx-1.24.0 - 克隆模块源码(确保其支持动态编译,新版大多已适配):
git clone https://github.com/openresty/echo-nginx-module.git - 配置构建系统(仅生成 makefile,不安装):
./configure --with-compat --add-dynamic-module=../echo-nginx-module - 执行
make modules(注意:不是make && make install)
成功后,objs/ngx_http_echo_module.so即生成
部署与启用模块
将生成的 .so 文件复制到 modules-path 目录,例如:
sudo cp objs/ngx_http_echo_module.so /usr/lib/nginx/modules/- 设置可读权限:
sudo chmod 644 /usr/lib/nginx/modules/ngx_http_echo_module.so - 在
nginx.conf的 main 上下文(events 块之前)添加:load_module /usr/lib/nginx/modules/ngx_http_echo_module.so; - 验证并重载:
nginx -t && nginx -s reload
不复杂但容易忽略:模块源码和 Nginx 源码版本必须严格一致;--with-compat 是第三方动态模块加载的硬性前提;make modules 是唯一正确命令,误用 make install 会覆盖现有安装。


















