需编译安装gmssl(如v3.1.1)并搭配nginx-gm等国密模块,配置sm2证书及ecdhe-sm2-with-sm4-sm3密码套件,原生nginx不支持国密。

要在 Nginx 中支持国密算法(SM2/SM3/SM4),需通过编译安装支持国密的 OpenSSL(如 OpenSSL 1.1.1t+ with GMSSL patch 或更推荐的 gmssl.org 官方分支),再配合支持国密的 Nginx 模块(如 nginx-gm 或 nginx-sm)完成。原生 Nginx 不支持国密,必须依赖 patched 的 OpenSSL 和适配的模块。
准备支持国密的 OpenSSL
国密功能需底层密码库支持。官方 OpenSSL 在 3.0+ 版本中已初步支持 SM2/SM3/SM4,但生产环境更常用经深度验证的 GMSSL(基于 OpenSSL 1.1.1 分支的国密增强版)。
- 下载 GMSSL 源码:
git clone https://github.com/gmssl/gmssl.git(注意选择稳定 release,如 v3.1.1) - 编译安装:
./config --prefix=/usr/local/gmssl --openssldir=/usr/local/gmssl shared zlib make -j$(nproc) sudo make install
- 验证是否启用国密算法:
/usr/local/gmssl/bin/openssl list -enabled -cipher-algorithms | grep -i sm应输出SM4-CBC、SM4-GCM、SM2等
获取并配置国密 Nginx 模块
主流选择是 nginx-gm(由天威诚信等机构维护,适配 GMSSL)或 nginx-sm(开源社区较活跃的轻量模块)。以 nginx-gm 为例:
- 克隆模块源码:
git clone https://github.com/tianyizhixin/nginx-gm.git - 确保模块版本与目标 Nginx 版本兼容(例如 nginx-gm v1.2.0 支持 Nginx 1.18–1.24)
- 不建议直接替换默认 ssl 模块,而是作为动态模块编译(Nginx ≥1.9.11):
./configure \ --with-openssl=/path/to/gmssl \ # 指向 GMSSL 源码目录(非安装路径) --with-openssl-opt="enable-gost" \ # 部分版本需显式开启 --add-dynamic-module=../nginx-gm \ --prefix=/usr/local/nginx \ --with-http_ssl_module
编译安装 Nginx 并加载模块
完成 configure 后执行编译安装,并在配置中启用国密模块:
- 运行:
make && sudo make install - 编辑
/usr/local/nginx/conf/nginx.conf,在http或server块中添加:ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers ECDHE-SM2-WITH-SM4-SM3:TLS_AES_256_GCM_SHA384; ssl_certificate /path/to/server_sm2.crt; ssl_certificate_key /path/to/server_sm2.key; ssl_trusted_certificate /path/to/ca_sm2.crt;
- 证书需为 SM2 签发(可用 GMSSL 工具生成):
gmssl req -x509 -sm2_id 1234567812345678 -newkey sm2 -keyout server_sm2.key -out server_sm2.crt
验证与常见问题
启动后用支持国密的客户端(如 GMSSL curl、国密浏览器)测试;服务端可通过日志和 OpenSSL 测试确认:
- 检查模块是否加载:
/usr/local/nginx/sbin/nginx -V 2>&1 | grep -o nginx-gm - 抓包验证 TLS 握手是否使用 SM2/SM4 密码套件(Wireshark + TLS 解密密钥)
- 若报错
unknown directive "ssl_ciphers":说明未正确启用--with-http_ssl_module;若提示no supported cipher:检查 OpenSSL 是否真含 SM 算法,且ssl_ciphers写法是否匹配(GMSSL 使用ECDHE-SM2-WITH-SM4-SM3格式)











