静态编译Nginx需三步协同:依赖源码与nginx源码平级;configure用--with-pcre=../pcre-x.x等指向源码目录启用静态构建;make后通过-static及.a路径强制静态链接libc等库,ldd验证为“not a dynamic executable”。

要指定编译安装静态链接版本的 Nginx,核心是让 ./configure 阶段强制将 PCRE、zlib、OpenSSL(如需 HTTPS)和 libc 全部以静态方式嵌入最终二进制,不依赖目标系统上的 .so 动态库。
关键不在“加个开关”,而在三步协同:源码同级准备、configure 参数精准控制、链接器行为显式约束。
✅ 准备依赖源码(必须与 nginx 源码平级)
Nginx 官方 configure 不接受预装的静态库路径,而是要求你把依赖源码解压在同一父目录下,它会自动识别并静态编译进去:
cd ~ wget https://nginx.org/download/nginx-1.30.4.tar.gz wget https://downloads.sourceforge.net/project/pcre/pcre/8.45/pcre-8.45.tar.gz wget https://zlib.net/zlib-1.3.2.tar.gz wget https://www.openssl.org/source/openssl-3.2.1.tar.gz tar -xzf nginx-1.30.4.tar.gz tar -xzf pcre-8.45.tar.gz tar -xzf zlib-1.3.2.tar.gz tar -xzf openssl-3.2.1.tar.gz
目录结构必须是:
~/ ├── nginx-1.30.4/ ├── pcre-8.45/ ├── zlib-1.3.2/ └── openssl-3.2.1/
⚠️ 注意:不能用系统
pcre-devel或zlib-devel包,也不能用--with-pcre=/path指向已编译库——那会导致动态链接。
✅ 运行 configure(启用静态链接关键参数)
进入 nginx 源码目录,执行:
cd nginx-1.30.4 ./configure \ --prefix=/opt/nginx-static \ --with-pcre=../pcre-8.45 \ --with-zlib=../zlib-1.3.2 \ --with-openssl=../openssl-3.2.1 \ --with-http_ssl_module \ --with-http_gzip_static_module \ --with-http_stub_status_module \ --without-http_rewrite_module # 可选:若不用正则,可省掉 PCRE(但一般保留)
重点说明:
-
--with-pcre=../pcre-8.45等路径必须是相对路径且指向源码目录(不是./configure生成的build/),Nginx 内部会调用其configure && make并静态链接。 -
--with-http_ssl_module是启用 HTTPS 的前提,它会触发 OpenSSL 静态编译。 - 不加
--with-pcre-jit(JIT 正则)更稳妥,避免某些 OpenSSL 版本冲突。
✅ 强制静态链接 libc(关键收尾动作)
默认 make 仍可能动态链接 glibc。要彻底静态,需在 make 前修改 objs/Makefile,或更可靠地——重写链接命令:
make clean # 确保干净 make # 修改链接行:将 -lcrypto -lssl -lz -lpcre 替换为完整静态路径,并加 -static sed -i 's/$(CC) -o/$(CC) -static -o/' objs/Makefile sed -i 's/-lpcre/-lpcre/.a/g' objs/Makefile sed -i 's/-lz/-lz/.a/g' objs/Makefile sed -i 's/-lssl -lcrypto/-lssl/.a -lcrypto/.a/g' objs/Makefile
或者更推荐:直接 make 后手动链接(确保你有 .a 静态库):
cd objs gcc -o nginx-static \ ngx_modules.o \ ../src/core/ngx_core.o ... #(略去大量 .o 文件)\ -L../pcre-8.45/.libs -lpcre \ -L../zlib-1.3.2 -lz \ -L../openssl-3.2.1/libcrypto/.libs -lcrypto \ -L../openssl-3.2.1/libssl/.libs -lssl \ -static -lm -lpthread -ldl
✅ 验证是否真静态:
ldd ./nginx-static应输出not a dynamic executable。
✅ 安装与验证
make install /opt/nginx-static/sbin/nginx -V # 查看编译参数是否含 --with-openssl=... /opt/nginx-static/sbin/nginx -t # 测试配置
拷贝 nginx-static/sbin/nginx 到任意同架构 Linux(如 CentOS、Ubuntu、Alpine)即可直接运行,无需安装任何依赖。
不复杂但容易忽略


















