1. Nginx服务管理基础概念
Nginx(发音为"engine-x")是一个高性能的HTTP和反向代理服务器,也是IMAP/POP3/SMTP代理服务器。它由俄罗斯程序员Igor Sysoev开发,最初是为解决C10K问题(即单机同时处理1万个连接的问题)而设计的。经过多年发展,Nginx已经成为全球最受欢迎的Web服务器之一,市场份额超过30%。
提示:Nginx与Apache最大的区别在于其事件驱动架构,这使得它在高并发场景下能够保持较低的资源消耗。
Nginx的核心优势主要体现在以下几个方面:
- 高并发处理能力:采用异步非阻塞的事件驱动模型
- 低内存消耗:相比传统服务器,处理相同请求时内存占用更少
- 高可靠性:即使在高负载下也能保持稳定运行
- 热部署能力:支持不停止服务的情况下更新配置和二进制文件
在实际生产环境中,Nginx通常被用于以下场景:
- 静态内容服务(如图片、HTML、CSS、JS文件)
- 反向代理和负载均衡
- API网关
- 缓存服务器
- 媒体流服务器(支持HLS、RTMP等协议)
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. Nginx安装与初始化配置
2.1 不同平台的安装方法
Linux系统安装(以Ubuntu为例)
bash复制# 更新软件包索引
sudo apt update
# 安装Nginx
sudo apt install nginx
# 启动Nginx服务
sudo systemctl start nginx
# 设置开机自启
sudo systemctl enable nginx
Windows系统安装
- 从Nginx官网下载Windows版本压缩包
- 解压到指定目录(建议路径不要包含中文或空格)
- 双击nginx.exe启动(控制台窗口保持打开状态)
Docker方式安装
bash复制docker pull nginx:latest
docker run --name my-nginx -p 80:80 -d nginx
2.2 安装后的基本验证
安装完成后,可以通过以下方式验证Nginx是否正常运行:
- 检查服务状态(Linux系统):
bash复制systemctl status nginx
-
访问默认页面:
在浏览器中输入服务器IP地址或域名,应该能看到Nginx欢迎页面。 -
检查端口监听:
bash复制netstat -tulnp | grep nginx
注意:如果遇到"nginx: command not found"错误,通常是因为Nginx的可执行文件路径未加入系统PATH环境变量中。可以通过find / -name nginx命令查找安装位置,然后创建符号链接到/usr/bin目录下。
2.3 目录结构与配置文件
Nginx的标准目录结构(Linux系统):
code复制/etc/nginx/
├── nginx.conf # 主配置文件
├── conf.d/ # 额外配置文件目录
├── sites-available/ # 可用站点配置
├── sites-enabled/ # 启用的站点配置(通常是符号链接)
├── modules/ # 动态模块目录
└── logs/ # 日志目录(实际可能在/var/log/nginx)
默认配置文件nginx.conf的主要结构:
nginx复制user www-data;
worker_processes auto;
pid /run/nginx.pid;
events {
worker_connections 768;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
3. Nginx服务管理操作
3.1 基本服务控制命令
systemd管理方式(现代Linux发行版)
bash复制# 启动服务
sudo systemctl start nginx
# 停止服务
sudo systemctl stop nginx
# 重启服务
sudo systemctl restart nginx
# 重新加载配置(不中断服务)
sudo systemctl reload nginx
# 查看服务状态
sudo systemctl status nginx
# 设置开机自启
sudo systemctl enable nginx
# 禁用开机自启
sudo systemctl disable nginx
传统SysVinit方式
bash复制# 适用于较老系统
sudo service nginx start
sudo service nginx stop
sudo service nginx restart
sudo service nginx reload
Windows系统管理
bash复制# 启动(在Nginx目录下)
start nginx
# 快速停止
nginx -s stop
# 优雅停止(处理完当前请求)
nginx -s quit
# 重新加载配置
nginx -s reload
# 重新打开日志文件
nginx -s reopen
3.2 进程管理与信号控制
Nginx主进程可以接收以下信号:
bash复制# 重新加载配置(等同于reload)
kill -HUP `cat /var/run/nginx.pid`
# 优雅关闭
kill -QUIT `cat /var/run/nginx.pid`
# 重新打开日志文件(用于日志轮转)
kill -USR1 `cat /var/run/nginx.pid`
# 平滑升级可执行文件
kill -USR2 `cat /var/run/nginx.pid`
3.3 日志管理
Nginx默认生成两种日志:
- 访问日志(access.log):记录所有客户端请求
- 错误日志(error.log):记录服务运行错误信息
日志轮转配置示例(使用logrotate):
bash复制/var/log/nginx/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 0640 www-data adm
sharedscripts
postrotate
[ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
endscript
}
4. Nginx高级服务管理技巧
4.1 性能调优参数
在nginx.conf中的调优参数示例:
nginx复制worker_processes auto; # 通常设置为CPU核心数
worker_rlimit_nofile 100000; # 每个worker能打开的文件描述符数量
events {
worker_connections 4096; # 每个worker的最大连接数
multi_accept on; # 一次接受所有新连接
use epoll; # Linux系统高性能事件模型
}
http {
sendfile on; # 启用零拷贝传输
tcp_nopush on; # 优化数据包发送
tcp_nodelay on; # 禁用Nagle算法
keepalive_timeout 65; # 保持连接超时时间
keepalive_requests 1000; # 单个连接的最大请求数
# 缓冲区设置
client_body_buffer_size 10K;
client_header_buffer_size 1k;
client_max_body_size 8m;
large_client_header_buffers 2 1k;
}
4.2 多实例部署
有时需要在同一台服务器上运行多个Nginx实例:
- 复制完整的Nginx安装目录
- 修改第二个实例的配置文件(更改监听端口和pid文件位置)
- 使用不同的启动参数:
bash复制/usr/sbin/nginx -c /path/to/alternate/config -p /path/to/alternate/prefix
4.3 动态模块管理
Nginx 1.9.11+支持动态加载模块:
bash复制# 查看已加载模块
nginx -V
# 编译动态模块
./configure --add-dynamic-module=/path/to/module
make modules
# 加载动态模块
load_module modules/ngx_http_modulename_module.so;
4.4 安全加固措施
- 隐藏Nginx版本信息:
nginx复制server_tokens off;
- 限制敏感文件访问:
nginx复制location ~ /\.ht {
deny all;
}
- 禁用不必要的HTTP方法:
nginx复制if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 405;
}
- 配置适当的权限:
bash复制chown -R root:www-data /etc/nginx
chmod -R 750 /etc/nginx
find /etc/nginx -type f -exec chmod 640 {} \;
5. 常见问题排查与解决
5.1 服务启动失败排查
- 检查错误日志:
bash复制tail -n 50 /var/log/nginx/error.log
- 测试配置文件语法:
bash复制nginx -t
- 检查端口冲突:
bash复制netstat -tulnp | grep :80
- 检查文件权限:
bash复制namei -l /var/log/nginx/error.log
5.2 性能问题诊断
- 查看活跃连接数:
bash复制netstat -an | grep :80 | wc -l
- 监控worker进程资源使用:
bash复制top -p `pgrep -d',' nginx`
- 分析慢请求:
nginx复制# 在http块中添加
log_format timed_combined '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time';
5.3 配置错误处理
常见错误:"unknown directive"
通常是因为:
- 拼写错误
- 指令放在了错误的配置块中
- 需要的模块没有编译或加载
location规则冲突
调试方法:
nginx复制# 在location中添加调试信息
add_header X-Location-Matched "your_location_name";
rewrite规则循环
检查方法:
nginx复制rewrite_log on; # 需要设置error_log级别为notice
6. 企业级Nginx服务管理实践
6.1 高可用架构设计
典型的高可用方案:
- Keepalived + Nginx主备模式
- Nginx集群 + DNS轮询
- 云环境下的负载均衡器 + 自动扩展组
Keepalived配置示例:
bash复制vrrp_script chk_nginx {
script "pidof nginx"
interval 2
weight 2
}
vrrp_instance VI_1 {
interface eth0
state MASTER
virtual_router_id 51
priority 101
virtual_ipaddress {
192.168.1.100
}
track_script {
chk_nginx
}
}
6.2 监控与告警
Prometheus监控配置:
- 安装nginx_exporter
- Nginx配置status模块:
nginx复制location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
关键监控指标:
- 活跃连接数(Active connections)
- 每秒请求数(Requests per second)
- 各状态连接数(Reading/Writing/Waiting)
- 上游服务器响应时间
- 错误率(4xx/5xx)
6.3 自动化部署与配置管理
使用Ansible管理Nginx配置的示例playbook:
yaml复制- hosts: webservers
become: yes
tasks:
- name: Install Nginx
apt:
name: nginx
state: latest
update_cache: yes
- name: Ensure Nginx config directory exists
file:
path: /etc/nginx/conf.d
state: directory
mode: '0755'
- name: Deploy site configuration
template:
src: templates/nginx-site.conf.j2
dest: /etc/nginx/conf.d/{{ domain }}.conf
validate: 'nginx -t -c %s'
notify: Reload Nginx
handlers:
- name: Reload Nginx
service:
name: nginx
state: reloaded
6.4 灰度发布与AB测试
使用Nginx实现流量分割:
nginx复制split_clients "${remote_addr}${http_user_agent}" $variant {
50% "v1";
50% "v2";
}
server {
location / {
if ($variant = "v1") {
proxy_pass http://backend_v1;
}
if ($variant = "v2") {
proxy_pass http://backend_v2;
}
}
}
7. Nginx与其他技术的集成
7.1 与PHP集成(PHP-FPM)
典型配置:
nginx复制location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php8.3-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
7.2 反向代理与负载均衡
基础反向代理配置:
nginx复制location / {
proxy_pass http://backend_server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
负载均衡示例:
nginx复制upstream backend {
least_conn; # 负载均衡算法
server backend1.example.com weight=5;
server backend2.example.com;
server backend3.example.com max_fails=3 fail_timeout=30s;
}
server {
location / {
proxy_pass http://backend;
}
}
7.3 与CDN集成
优化CDN回源配置:
nginx复制# 识别CDN IP并设置真实客户端IP
set_real_ip_from 192.0.2.0/24;
real_ip_header X-Forwarded-For;
real_ip_recursive on;
# 缓存控制头
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 365d;
add_header Cache-Control "public, no-transform";
}
7.4 流媒体服务配置
HLS流媒体配置示例:
nginx复制rtmp {
server {
listen 1935;
chunk_size 4096;
application live {
live on;
record off;
hls on;
hls_path /tmp/hls;
hls_fragment 3;
hls_playlist_length 60;
}
}
}
http {
server {
location /hls {
types {
application/vnd.apple.mpegurl m3u8;
video/mp2t ts;
}
root /tmp;
add_header Cache-Control no-cache;
}
}
}
8. Windows系统下的Nginx服务管理
8.1 安装为Windows服务
使用第三方工具winsw将Nginx安装为Windows服务:
- 下载winsw.exe并重命名为nginx-service.exe
- 创建同名的xml配置文件:
xml复制<service>
<id>nginx</id>
<name>Nginx</name>
<description>Nginx HTTP Server</description>
<executable>nginx.exe</executable>
<logpath>logs</logpath>
<logmode>roll</logmode>
<depend></depend>
<startargument>-p</startargument>
<startargument>C:\nginx</startargument>
<stopexecutable>nginx.exe</stopexecutable>
<stopargument>-p</stopargument>
<stopargument>C:\nginx</stopargument>
<stopargument>-s</stopargument>
<stopargument>stop</stopargument>
</service>
- 安装服务:
cmd复制nginx-service.exe install
8.2 Windows下的性能优化
- 调整worker_processes数量(通常设置为CPU核心数)
- 关闭日志文件缓冲:
nginx复制access_log logs/access.log combined buffer=0;
- 使用sendfile off(Windows下sendfile实现不如Linux高效)
- 调整事件模型:
nginx复制use select; # Windows下唯一可用的事件模型
8.3 常见Windows特有问题
端口占用问题
cmd复制netstat -ano | findstr :80
tasklist | findstr <PID>
路径问题
- 确保配置文件中使用正斜杠(/)或双反斜杠(\)
- 避免路径中包含空格
权限问题
- 以管理员身份运行cmd
- 检查防火墙设置
9. Nginx版本升级与维护
9.1 平滑升级流程
- 备份当前配置和二进制文件
- 下载新版本并编译(保持配置参数一致)
- 替换旧二进制文件
- 发送USR2信号给主进程:
bash复制kill -USR2 `cat /var/run/nginx.pid`
- 发送WINCH信号给旧主进程,优雅关闭旧worker:
bash复制kill -WINCH `cat /var/run/nginx.pid.oldbin`
- 测试新版本运行正常后,可以关闭旧主进程:
bash复制kill -QUIT `cat /var/run/nginx.pid.oldbin`
9.2 模块管理与定制编译
查看当前编译参数:
bash复制nginx -V
典型定制编译流程:
bash复制./configure \
--prefix=/etc/nginx \
--sbin-path=/usr/sbin/nginx \
--modules-path=/usr/lib/nginx/modules \
--conf-path=/etc/nginx/nginx.conf \
--error-log-path=/var/log/nginx/error.log \
--http-log-path=/var/log/nginx/access.log \
--pid-path=/var/run/nginx.pid \
--lock-path=/var/run/nginx.lock \
--http-client-body-temp-path=/var/cache/nginx/client_temp \
--http-proxy-temp-path=/var/cache/nginx/proxy_temp \
--http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp \
--http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp \
--http-scgi-temp-path=/var/cache/nginx/scgi_temp \
--user=nginx \
--group=nginx \
--with-http_ssl_module \
--with-http_realip_module \
--with-http_addition_module \
--with-http_sub_module \
--with-http_dav_module \
--with-http_flv_module \
--with-http_mp4_module \
--with-http_gunzip_module \
--with-http_gzip_static_module \
--with-http_random_index_module \
--with-http_secure_link_module \
--with-http_stub_status_module \
--with-http_auth_request_module \
--with-threads \
--with-stream \
--with-stream_ssl_module \
--with-http_slice_module \
--with-mail \
--with-mail_ssl_module \
--with-file-aio \
--with-http_v2_module \
--with-cc-opt='-g -O2 -fstack-protector-strong -Wformat -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -fPIC' \
--with-ld-opt='-Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-z,now -Wl,--as-needed -pie'
make
sudo make install
9.3 回滚方案
- 保留旧版本的二进制文件
- 如果新版本出现问题:
bash复制# 停止新版本
kill -QUIT `cat /var/run/nginx.pid`
# 启动旧版本
/usr/sbin/nginx.old -c /etc/nginx/nginx.conf
# 发送HUP信号重新加载worker
kill -HUP `cat /var/run/nginx.pid`
10. Nginx安全加固与最佳实践
10.1 SSL/TLS配置最佳实践
nginx复制ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384';
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
ssl_session_tickets off;
ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout 5s;
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
add_header X-Frame-Options DENY;
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1; mode=block";
10.2 访问控制与速率限制
基础访问控制:
nginx复制location /admin {
allow 192.168.1.0/24;
deny all;
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
速率限制:
nginx复制limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
server {
location /api/ {
limit_req zone=one burst=20 nodelay;
proxy_pass http://api_backend;
}
}
10.3 防DDoS与恶意请求
限制连接数:
nginx复制limit_conn_zone $binary_remote_addr zone=addr:10m;
location /download {
limit_conn addr 5;
}
过滤恶意User-Agent:
nginx复制map $http_user_agent $blocked_agent {
default 0;
~*(wget|curl|python-requests) 1;
~*(nikto|sqlmap|nmap) 1;
}
server {
if ($blocked_agent) {
return 403;
}
}
10.4 日志分析与安全审计
使用goaccess进行实时日志分析:
bash复制goaccess /var/log/nginx/access.log --log-format=COMBINED --real-time-html --port=7890
关键安全审计点:
- 异常的User-Agent
- 高频的404错误
- 敏感路径访问尝试
- 异常的HTTP方法
- 来源IP异常行为
11. Nginx与容器化部署
11.1 Docker基础部署
基本Docker运行命令:
bash复制docker run -d --name nginx \
-p 80:80 \
-p 443:443 \
-v /path/to/nginx.conf:/etc/nginx/nginx.conf \
-v /path/to/html:/usr/share/nginx/html \
-v /path/to/logs:/var/log/nginx \
nginx:latest
11.2 Kubernetes中的Nginx部署
基础Deployment配置:
yaml复制apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:latest
ports:
- containerPort: 80
volumeMounts:
- name: nginx-config
mountPath: /etc/nginx/nginx.conf
subPath: nginx.conf
volumes:
- name: nginx-config
configMap:
name: nginx-config
11.3 容器化环境下的配置管理
使用ConfigMap管理Nginx配置:
bash复制# 从文件创建ConfigMap
kubectl create configmap nginx-config --from-file=nginx.conf
# 更新ConfigMap
kubectl create configmap nginx-config --from-file=nginx.conf -o yaml --dry-run=client | kubectl replace -f -
# 触发Pod重新加载配置(不重启容器)
kubectl exec -it <pod-name> -- nginx -s reload
11.4 容器化性能优化
- 调整worker_processes为auto
- 禁用access_log或输出到stdout
- 使用共享内存zone进行负载均衡状态共享
- 调整内核参数:
bash复制sysctl -w net.core.somaxconn=65535
sysctl -w net.ipv4.tcp_max_syn_backlog=65535
12. Nginx与微服务架构
12.1 API网关模式
基础API网关配置:
nginx复制location /api/user {
proxy_pass http://user-service;
}
location /api/order {
proxy_pass http://order-service;
}
location /api/payment {
proxy_pass http://payment-service;
}
12.2 服务发现集成
与Consul集成的动态配置:
nginx复制resolver consul:8500;
set $service_endpoint "";
location /api {
rewrite_by_lua_block {
local consul = require "resty.consul"
local c = consul:new()
local ok, err = c:connect("consul", 8500)
if not ok then
ngx.log(ngx.ERR, "failed to connect to Consul: ", err)
return ngx.exit(500)
end
local res, err = c:get_service("my-service")
if not res then
ngx.log(ngx.ERR, "failed to get service: ", err)
return ngx.exit(503)
end
ngx.var.service_endpoint = res[1].ServiceAddress .. ":" .. res[1].ServicePort
}
proxy_pass http://$service_endpoint;
}
12.3 金丝雀发布策略
基于权重的流量分配:
nginx复制upstream backend {
server backend-v1 weight=90;
server backend-v2 weight=10;
}
基于Header的流量路由:
nginx复制map $http_x_canary $backend {
default "backend-v1";
"true" "backend-v2";
}
server {
location / {
proxy_pass http://$backend;
}
}
12.4 微服务监控与追踪
集成OpenTelemetry:
nginx复制load_module modules/ngx_http_opentelemetry_module.so;
http {
opentelemetry on;
opentelemetry_config {
exporter otlp;
endpoint otel-collector:4317;
service_name nginx;
resource_attributes "deployment.environment=production";
sampler parentbased_always_on;
}
server {
location / {
opentelemetry_operation_name "http:$request_method:$uri";
proxy_pass http://backend;
}
}
}
13. Nginx性能调优实战
13.1 操作系统级优化
- 调整文件描述符限制:
bash复制echo "worker_rlimit_nofile 100000;" >> /etc/nginx/nginx.conf
ulimit -n 100000
- 调整内核参数:
bash复制# /etc/sysctl.conf
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_tw_reuse = 1
net.ipv4.ip_local_port_range = 1024 65535
- 禁用透明大页:
bash复制echo never > /sys/kernel/mm/transparent_hugepage/enabled
13.2 Nginx核心参数调优
nginx复制events {
worker_connections 10000;
multi_accept on;
use epoll;
}
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
# 缓冲区优化
client_body_buffer_size 10K;
client_header_buffer_size 1k;
client_max_body_size 8m;
large_client_header_buffers 4 8k;
# 连接优化
keepalive_timeout 30;
keepalive_requests 10000;
# MIME类型缓存
open_file_cache max=2000 inactive=20s;
open_file_cache_valid 60s;
open_file_cache_min_uses 5;
open_file_cache_errors off;
}
13.3 缓存策略优化
代理缓存配置:
nginx复制proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m inactive=60m use_temp_path=off;
server {
location / {
proxy_cache my_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
proxy_cache_background_update on;
proxy_cache_lock on;
add_header X-Cache-Status $upstream_cache_status;
proxy_pass http://backend;
}
}
13.4 压力测试与瓶颈分析
使用wrk进行压力测试:
bash复制wrk -t12 -c400 -d30s http://localhost/
关键性能指标分析:
- 吞吐量(Requests/sec)
- 延迟分布(Latency)
- 错误率
- 系统资源使用情况(CPU、内存、IO)
性能瓶颈排查工具:
- top/htop - 查看CPU和内存使用
- vmstat 1 - 查看系统整体状态
- iostat -x 1 - 查看磁盘IO
- dstat - 综合监控
- nginx-status - 查看活跃连接数
14. Nginx与国密算法实践
14.1 国密SSL证书配置
使用GMSSL编译Nginx:
bash复制./configure --with-openssl=/path/to/gmssl \
--with-http_ssl_module \
--with-stream \
--with-stream_ssl_module
国密证书配置示例:
nginx复制server {
listen 443 ssl;
ssl_certificate /etc/nginx/ssl/server_sign.crt;
ssl_certificate_key /etc/nginx/ssl/server_sign.key;
ssl_certificate /etc/nginx/ssl/server_enc.crt;
ssl_certificate_key /etc/nginx/ssl/server_enc.key;
# 国密套件
ssl_ciphers 'ECC-SM2-WITH-SM4-SM3:ECDHE-SM2-WITH-SM4-SM3';
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
}
14.2 国密算法性能优化
- 启用硬件加速(如果可用):
nginx复制ssl_engine gmtls;
- 会话复用优化:
nginx复制ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
- 双证书链优化:
nginx复制ssl_certificate /path/to/sm2/sign.crt;
ssl_certificate /path/to/sm2/enc.crt;
ssl_certificate_key /path/to/sm2/sign.key;
ssl_certificate_key /path/to/sm2/enc.key;
14.3 兼容性处理
混合加密方案配置:
nginx复制server {
listen 443 ssl;
# 国密配置
ssl_certificate sm2.crt;
ssl_certificate_key sm2.key;
ssl_ciphers 'ECC-SM2-WITH-SM4-SM3:ECDHE-SM2-WITH-SM4-SM3';
# RSA兼容配置
ssl_certificate rsa.crt;
ssl_certificate_key rsa.key;
ssl_ciphers 'RSA+AESGCM:RSA+AES';
# 根据客户端能力选择
ssl_prefer_server_ciphers on;
}
15. Nginx与边缘计算
15.1 边缘缓存配置
动态内容边缘缓存:
nginx复制proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=edge_cache:10m inactive=5m use_temp_path=off;
server {
location / {
proxy_cache edge_cache;
proxy_cache_key "$scheme$request_method$host$request_uri$http_x_device_type";
proxy_cache_valid 200 302 5m;
proxy_cache_use_stale error timeout invalid_header updating http_500 http_502 http_503 http_504;
proxy_cache_background_update on;
proxy_pass http://origin;
}
}
15.2 边缘计算逻辑
使用nginScript实现简单边缘逻辑:
nginx复制js_include /etc/nginx/edge.js;
server {
location / {
js_content processRequest;
}
}
edge.js示例:
javascript复制function processRequest(r) {
var device = r.headersIn['User-Agent'].match(/Mobile/) ? 'mobile' : 'desktop';
if (device === 'mobile') {
r.headersOut['X-Edge-Transform'] = 'mobile-optimized';
r.internalRedirect('@mobile');
} else {
r.headersOut['X-Edge-Transform'] = 'desktop';
r.internalRedirect('@desktop');
}
}
15.3 边缘AI集成
使用Nginx+Lua集成TensorFlow Serving:
nginx复制location /ai/predict {
content_by_lua_block {
local http = require "resty.http"
local httpc = http.new()
-- 预处理请求
local image_data = ngx.req.get_body_data()
local preprocessed = preprocess_image(image_data)
-- 调用AI服务
local res, err = httpc:request_uri("http://ai-service:8501/v1/models/default:predict", {
method = "POST",
body = json.encode({instances={preprocessed}}),
headers = {["Content-Type"] = "application/json"}
})
-- 后处理响应
local result = process_prediction(res.body)
ngx.say(json.encode(result))
}
}
15.4 边缘数据分析
实时日志分析配置:
nginx复制log_format edge_analytics '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time '
'$geoip_country_code $device_type';
server {
access_log /var/log/nginx/edge.log edge_analytics;
location = /analytics {
content_by_lua_block {
local analytics = require "edge_analytics"
local results = analytics.process("/var/log/nginx/edge.log")
ngx.say(json.encode(results))
}
}
}
16. Nginx在特殊场景下的应用
16.1 大文件分片上传
nginx复制client_max_body_size 0; # 禁用大小限制
location /upload {
