编译精简版Nginx需显式禁用非必要模块:一、安装基础依赖并获取纯净源码;二、禁用HTTP功能模块;三、禁用MAIL与STREAM模块;四、剥离调试符号并优化链接;五、验证模块剔除效果。

如果您希望编译一个精简版的 Nginx,仅保留必需功能以显著减小二进制文件体积,则需在 configure 阶段显式禁用默认启用的非必要模块。以下是具体操作步骤:
一、预检依赖与源码准备
在执行模块化编译前,需确认系统已安装基础构建工具及可选依赖,并获取纯净的官方 Nginx 源码包。跳过非必需依赖可避免隐式启用关联模块。
1、执行 apt-get install build-essential libpcre3-dev zlib1g-dev -y(Debian/Ubuntu)或 yum groupinstall "Development Tools" && yum install pcre-devel zlib-devel -y(CentOS/RHEL),仅安装编译核心依赖。
2、使用 wget https://nginx.org/download/nginx-1.24.0.tar.gz 下载稳定版源码,解压后进入目录,不运行任何补丁脚本或第三方构建工具。
二、禁用默认 HTTP 功能模块
Nginx 默认启用大量 HTTP 处理模块,如访问控制、重写、代理等,若仅需静态文件服务,这些模块均可安全剔除,直接减少约 35% 的目标文件体积。
1、在源码根目录执行 configure 命令,添加 --without-http_access_module --without-http_auth_basic_module --without-http_autoindex_module --without-http_geo_module --without-http_map_module --without-http_split_clients_module --without-http_referer_module --without-http_rewrite_module --without-http_scgi_module --without-http_secure_link_module --without-http_slowlog_module --without-http_upstream_hash_module --without-http_upstream_ip_hash_module --without-http_upstream_least_conn_module --without-http_upstream_random_module --without-http_upstream_keepalive_module --without-http_upstream_zone_module 参数。
2、确认输出中显示 checking for PCRE library ... found 和 checking for ZLIB library ... found,且无 module not found 类警告。
三、禁用默认 MAIL 与 STREAM 模块
MAIL 和 STREAM 模块默认不参与构建,但若 configure 被意外触发相关检测(如存在 mail_ssl_module 依赖),可能引入冗余对象。显式关闭可确保零字节关联代码嵌入。
1、在 configure 命令中追加 --without-mail_pop3_module --without-mail_imap_module --without-mail_smtp_module --without-stream_limit_conn_module --without-stream_access_module --without-stream_geo_module --without-stream_map_module --without-stream_return_module --without-stream_split_clients_module --without-stream_ssl_module --without-stream_ssl_preread_module。
2、检查 configure 输出末尾的 summary 行,确认 mail modules: no 和 stream modules: no 明确标示为 disabled。
四、剥离调试符号与优化链接
configure 生成的 Makefile 默认保留调试信息并采用未优化链接方式,导致二进制膨胀。通过覆盖 CFLAGS 与链接器选项可进一步压缩最终产物。
1、在 configure 后、make 前,执行 export CFLAGS="-O2 -s -fdata-sections -ffunction-sections" 和 export LDFLAGS="-Wl,--gc-sections -s"。
2、运行 make -j$(nproc) 编译,完成后执行 strip objs/nginx 对主二进制文件进行符号剥离。
五、验证模块剔除效果
编译完成后需验证实际加载模块是否符合预期,避免因依赖关系导致隐式启用残留模块。直接检查二进制导出符号比运行时查询更可靠。
1、执行 ./objs/nginx -V 2>&1 | grep -E "(built|configure)",核对输出中的 configure arguments 是否完整包含所有 --without-* 参数。
2、运行 nm -D ./objs/nginx | grep -E "(http|mail|stream|ngx_http|ngx_mail|ngx_stream)" | wc -l,若返回值为 0,表明对应模块符号已完全移除。










