源码编译时禁用非必要模块是降低 nginx 内存占用最根本有效的方式,需通过 configure 参数剔除未使用的 http、mail、stream 等模块,并避免安装冗余依赖,最终精简二进制体积与攻击面。

直接在编译阶段精简模块,是源码安装时降低 Nginx 内存占用最根本、最有效的方式。不是靠后期配置“关掉”功能,而是让那些没用的代码压根不进二进制文件——既省内存,又减体积,还少攻击面。
明确哪些模块可以安全禁用
多数轻量 Web 服务(静态托管、反向代理、HTTPS 终结)只需 http_core、ngx_http_upstream_module、ngx_http_proxy_module 和基础 SSL 支持。其余模块若未在配置中显式使用,就该在 configure 时剔除:
HTTP 类(最常增重):
--without-http_autoindex_module(禁目录列表)--without-http_ssi_module(不用服务器端包含)--without-http_geo_module和--without-http_map_module(无 IP 映射或变量映射需求)--without-http_rewrite_module(不用rewrite/if/return,改用try_files或 CDN 路由)--without-http_scgi_module、--without-http_uwsgi_module、--without-http_fastcgi_module(不对接非 HTTP 后端)非核心功能类(建议全关):
--without-mail_pop3_module --without-mail_imap_module --without-mail_smtp_module(不做邮件代理)--without-stream_module(不用 TCP/UDP 四层转发)--without-http_perl_module --without-http_xslt_module(生产环境极少用)编译与调试类(可选但推荐):
--without-debug(去掉调试符号,减少约 15% 二进制体积)--with-cc-opt='-O2'(启用 GCC 优化,提升性能且不增内存)
只装必需依赖,避免隐式启用模块
CentOS/RHEL:
yum install pcre-devel zlib-devel openssl-devel -y
Debian/Ubuntu:
apt install libpcre3-dev zlib1g-dev libssl-dev -y
不装 libgeoip-dev、libxml2-dev、perl-dev 等,否则 configure 可能自动启用关联模块。
编译命令示例(精简实用型)
./configure \ --prefix=/usr/local/nginx-min \ --with-http_ssl_module \ --with-http_v2_module \ --with-http_realip_module \ --without-http_autoindex_module \ --without-http_ssi_module \ --without-http_geo_module \ --without-http_map_module \ --without-http_rewrite_module \ --without-http_scgi_module \ --without-http_uwsgi_module \ --without-http_fastcgi_module \ --without-mail_pop3_module \ --without-mail_imap_module \ --without-mail_smtp_module \ --without-stream_module \ --without-debug \ --with-cc-opt='-O2' make && make install
验证是否生效
- 运行
nginx-min -V,检查输出末尾的configure arguments,确认目标--without-*参数已出现; - 执行
nginx-min -t确保语法无误; - 对比精简前后
ps aux | grep nginx的 RES 值,单 worker 通常下降 2–6 MB; -
ldd $(which nginx-min) | wc -l可粗略看动态依赖数,精简后一般减少 4–8 个。
不复杂但容易忽略











