Nginx编译时需显式启用gzip和stub_status模块:下载完整源码包,configure添加--with-http_gzip_static_module和--with-http_stub_status_module参数,安装zlib-devel,配置nginx.conf并验证模块加载成功。

如果您在编译 Nginx 源码时发现 gzip 压缩、连接状态监控等功能不可用,则很可能是对应模块未在 configure 阶段启用。以下是为 Nginx 编译阶段启用 Gzip、StubStatus 等核心模块的具体操作步骤:
一、确认源码版本并下载完整包
Nginx 官方主干版本默认不启用部分可选模块,需通过 configure 显式声明。使用官方 tar.gz 源码包可确保模块文件完整存在,避免因精简版缺失 stub_status 或 http_gzip_static 等目录导致编译失败。
1、访问 https://nginx.org/download/ 获取最新稳定版源码链接(如 nginx-1.24.0.tar.gz)。
2、执行 wget https://nginx.org/download/nginx-1.24.0.tar.gz 下载源码压缩包。
3、运行 tar -zxvf nginx-1.24.0.tar.gz && cd nginx-1.24.0 解压并进入源码目录。
二、启用 Gzip 相关模块的 configure 参数
Gzip 功能依赖三个关键模块:http_gzip_module(基础压缩)、http_gzip_static_module(预压缩文件支持)、http_ssl_module(HTTPS 下 gzip 兼容性保障)。其中前两者需显式开启,后者虽非 gzip 直接依赖,但生产环境通常必须启用。
1、执行 ./configure --with-http_gzip_static_module --with-http_ssl_module --with-http_v2_module 启用 gzip 静态支持与现代协议栈。
2、若需支持 .gz 文件自动匹配(如访问 /style.css 自动返回 /style.css.gz),还需确保系统已安装 zlib-devel 包:yum install -y zlib-devel(CentOS)或 apt-get install -y zlib1g-dev(Ubuntu)。
3、运行 make && sudo make install 完成编译安装。
三、启用 StubStatus 模块并配置监控端点
StubStatus 模块提供基础连接状态指标(如活跃连接数、已接受/处理请求数),其功能由 http_stub_status_module 实现,该模块不默认开启,且不依赖第三方库,仅需 configure 显式激活。
1、在 configure 命令中加入 --with-http_stub_status_module 参数,例如:./configure --with-http_stub_status_module --with-http_gzip_static_module。
2、编译安装后,在 nginx.conf 的 server 或 location 块中添加:location /nginx_status { stub_status on; access_log off; } 。
3、重载配置:sudo nginx -s reload,随后可通过 curl http://127.0.0.1/nginx_status 查看实时状态。
四、验证模块是否成功编入二进制文件
编译完成后,Nginx 二进制文件是否真正包含目标模块,不能仅凭 configure 输出判断,需通过命令行工具直接检查符号表或模块列表。
1、执行 /usr/local/nginx/sbin/nginx -V 2>&1 | grep -o with-http_.*_module,输出应包含 with-http_gzip_static_module 与 with-http_stub_status_module。
2、若需进一步确认,运行 strings /usr/local/nginx/sbin/nginx | grep -i gzip,应返回多个含 gzip 的字符串,表明模块代码已静态链接。
3、检查错误日志:tail -f /usr/local/nginx/logs/error.log,启动时若无 “unknown directive ‘stub_status’” 类报错,即表示模块加载成功。









