源码编译安装 Nginx 并添加第三方模块需先获取源码、配置时用 --add-module 指定路径、再 make && sudo make install;注意依赖、路径正确性及版本兼容性。

源码编译安装 Nginx 并添加第三方模块,核心在于:先获取 Nginx 源码和目标模块源码,再在 ./configure 阶段通过 --add-module 显式指定模块路径,最后编译安装。整个过程不依赖包管理器,灵活性高,但需注意依赖、路径和版本兼容性。
准备编译环境与依赖
确保系统已安装基础编译工具和库:
- 安装 GCC、make、perl、zlib、openssl、pcre 开发包(如 CentOS 执行
yum groupinstall "Development Tools",再装yum install zlib-devel openssl-devel pcre-devel;Ubuntu/Debian 用apt install build-essential zlib1g-dev libssl-dev libpcre3-dev) - 确认
which gcc、which make可用,避免因环境缺失导致./configure报错 - 非 root 用户操作时,建议全程使用普通用户,仅在
make install阶段用sudo
下载并解压 Nginx 与第三方模块源码
务必选择稳定版本,并保持源码目录结构清晰:
- 从 nginx.org 下载所需 Nginx 源码(如
nginx-1.24.0.tar.gz),解压至工作目录(如~/src/nginx-1.24.0) - 第三方模块通常托管在 GitHub,例如
echo-nginx-module:git clone https://github.com/openresty/echo-nginx-module.git ~/src/echo-nginx-module - 模块必须是源码形式(含
config文件),不能是预编译的二进制或已集成进其他发行版的打包版本
配置编译参数并添加模块
进入 Nginx 源码根目录,运行 ./configure,关键是要正确传递 --add-module:
- 基础配置示例(启用常用功能 + 添加 echo 模块):
./configure \<br> --prefix=/usr/local/nginx \<br> --with-http_ssl_module \<br> --with-http_v2_module \<br> --with-http_realip_module \<br> --add-module=../echo-nginx-module
注意:--add-module后跟的是相对路径(相对于当前 configure 所在目录),也可用绝对路径(如/home/user/src/echo-nginx-module) - 若添加多个模块,重复使用
--add-module参数,顺序无关,但需确保每个路径真实存在且可读 - 执行后检查输出末尾是否出现
checking for echo module ... found类提示,确认模块被识别;若报错 “no config file found”,说明模块路径错误或不兼容当前 Nginx 版本
编译安装并验证模块生效
完成配置后,依次执行编译与安装:
-
make—— 编译过程较慢,耐心等待;若报错,重点看第一处 error,常因缺少头文件、函数签名不匹配或模块与 Nginx 版本不兼容引起 -
sudo make install—— 默认安装到--prefix指定路径,配置文件在/usr/local/nginx/conf/nginx.conf - 验证模块是否加载:
/usr/local/nginx/sbin/nginx -V 2>&1 | grep -o with-http-echo-module,有输出即表示编译时已包含 - 在
nginx.conf的server块中加入测试指令,如location /hello { echo "Hello from echo module!"; },重启 Nginx 后访问curl http://localhost/hello看是否返回预期内容
整个流程不复杂但容易忽略细节:模块路径写错、依赖未装全、Nginx 和模块版本不匹配是最常见三类问题。建议首次操作时严格按步骤来,成功一次后即可复用模式添加其他模块。


















