源码安装是给nginx添加模块最直接、最可控的方式,需在./configure阶段显式启用内置模块(如--with-http_stub_status_module)或通过--add-module引入第三方模块,并依赖pcre、openssl等开发库完成编译安装。

源码安装是给 Nginx 添加模块最直接、最可控的方式。预编译包(如 yum 或 apt 安装的)默认只带基础模块,而像 http_stub_status_module、http_realip_module、第三方模块(如 nginx-sticky-module 或 lua-nginx-module)都必须在编译阶段显式加入。
确认模块类型:内置模块还是第三方模块
内置模块(如 --with-http_ssl_module、--with-http_v2_module)已随 Nginx 源码发布,只需在 ./configure 时启用即可;第三方模块需单独下载源码,并用 --add-module 引入。
- 常见内置模块启用方式:
--with-http_ssl_module(HTTPS 支持)--with-http_v2_module(HTTP/2)--with-http_realip_module(获取真实客户端 IP)--with-http_stub_status_module(状态页/status) - 第三方模块需先获取源码,例如:
git clone https://github.com/openresty/lua-nginx-module.gitgit clone https://github.com/yaoweibin/nginx-sticky-module.git
准备依赖和编译环境
缺少底层库会导致 configure 失败或模块不可用。不同系统安装命令略有差异:
- Ubuntu/Debian:
sudo apt update && sudo apt install -y build-essential libpcre3-dev libssl-dev zlib1g-dev - CentOS/RHEL/Rocky/Alma:
sudo dnf groupinstall -y "Development Tools" && sudo dnf install -y pcre-devel openssl-devel zlib-devel
注意:若要静态链接特定版本的 OpenSSL 或 PCRE(比如修复 CVE 或兼容旧系统),可下载对应源码并用 --with-openssl=/path/to/openssl 或 --with-pcre=/path/to/pcre 指定路径。
配置、编译与安装
进入解压后的 Nginx 源码目录(如 nginx-1.25.3/),执行 ./configure 命令,把需要的模块全部列进去:
- 启用多个内置模块示例:
./configure --prefix=/usr/local/nginx \<br> --user=nginx --group=nginx \<br> --with-http_ssl_module \<br> --with-http_v2_module \<br> --with-http_realip_module \<br> --with-http_stub_status_module \<br> --with-http_gzip_static_module \<br> --with-stream \<br> --with-stream_ssl_module - 添加第三方模块(以 lua-nginx-module 为例):
--add-module=/path/to/lua-nginx-module
注意路径必须是绝对路径,且该目录下需含config文件。 - 执行编译与安装:
make -j$(nproc)(并行加速)sudo make install
验证模块是否生效
安装完成后不能直接认为模块已就绪,必须验证:
- 检查已编译模块列表:
/usr/local/nginx/sbin/nginx -V 2>&1 | grep -o with-http.*_module
或运行/usr/local/nginx/sbin/nginx -V查看完整 configure 参数 - 测试配置语法(尤其新模块可能引入新指令):
/usr/local/nginx/sbin/nginx -t - 启动后访问
http://your-ip/status(需在配置中开启 stub_status)或查看 error.log 是否报模块加载错误
模块一旦编译进二进制,就无法动态增删——下次要加其他模块,必须重新 configure → make → make install。











