摘要:本文是 Nginx 进阶开发指南,涵盖性能优化、安全配置、日志管理、缓存配置、WebSocket 代理和高级负载均衡。通过本文档,你将掌握 Nginx 的高级特性,能够处理复杂的生产环境需求。
关键词:Nginx、性能优化、安全配置、日志管理、缓存、WebSocket、高级负载均衡
适合人群:有 Nginx 基础的开发者、运维工程师、想深入学习 Nginx 的工程师
阅读时间:约 45 分钟
版本信息:Nginx 1.24+ | 支持 Windows/Linux/macOS
文章目录
- 1. 性能优化
- 1.1 工作进程优化
- 1.2 文件传输优化
- 1.3 缓冲区优化
- 1.4 连接池优化
- 2. 安全配置
- 2.1 隐藏 Nginx 版本信息
- 2.2 限制请求大小
- 2.3 限制访问频率
- 2.4 IP 黑白名单
- 2.5 防止常见攻击
- 2.6 CORS 跨域配置
- 3. 日志管理
- 3.1 访问日志配置
- 3.2 错误日志配置
- 3.3 按域名分离日志
- 3.4 日志轮转配置
- 4. 缓存配置
- 4.1 代理缓存
- 4.2 缓存清除
- 5. WebSocket 代理
- 5.1 基础 WebSocket 代理
- 5.2 WebSocket 负载均衡
- 6. 高级负载均衡
- 6.1 健康检查
- 6.2 动态权重调整
- 6.3 区域会话保持
- 7. 实战案例
- 实战 1:高并发 API 网关
- 实战 2:微服务网关
- 实战 3:文件上传服务器
- 8. 常见问题 FAQ
- 9. 学习资源与建议
- 学习建议
- 官方资源
- 推荐工具
1. 性能优化
1.1 工作进程优化
合理配置工作进程数和连接数,提升并发处理能力:
# 自动检测 CPU 核心数 worker_processes auto; # 绑定工作进程到 CPU 核心(可选) worker_cpu_affinity auto; events { # 每个工作进程的最大连接数 worker_connections 2048; # 使用 epoll 模型(Linux) use epoll; # 尽可能多地接受新连接 multi_accept on; }优化建议:
| 配置项 | 推荐值 | 说明 |
|---|---|---|
worker_processes | auto或 CPU 核心数 | 充分利用多核 CPU |
worker_connections | 1024-4096 | 根据服务器性能调整 |
use epoll | epoll(Linux) | 高性能事件模型 |
multi_accept | on | 一次接受多个连接 |
1.2 文件传输优化
优化文件传输,减少系统调用:
http { # 启用高效文件传输 sendfile on; # 配合 sendfile 使用 tcp_nopush on; # 禁用 Nagle 算法,减少延迟 tcp_nodelay on; # 连接超时时间 keepalive_timeout 65; # 客户端请求体超时 client_body_timeout 12; # 客户端头超时 client_header_timeout 12; # 发送响应超时 send_timeout 10; }1.3 缓冲区优化
合理设置缓冲区大小,避免磁盘 I/O:
http { # 客户端请求头缓冲区 client_header_buffer_size 1k; large_client_header_buffers 4 4k; # 代理缓冲区 proxy_buffer_size 4k; proxy_buffers 8 4k; proxy_busy_buffers_size 8k; # FastCGI 缓冲区(PHP) fastcgi_buffer_size 4k; fastcgi_buffers 8 4k; fastcgi_busy_buffers_size 8k; }1.4 连接池优化
复用后端连接,减少连接开销:
upstream backend { server 127.0.0.1:3000; # 保持与后端的空闲连接 keepalive 32; } server { location / { proxy_pass http://backend; # 必需的配置 proxy_http_version 1.1; proxy_set_header Connection ""; } }💡提示:连接池可以显著提升性能,特别是后端响应时间较短的场景。
2. 安全配置
2.1 隐藏 Nginx 版本信息
避免暴露服务器信息:
http { # 隐藏 Nginx 版本号 server_tokens off; }2.2 限制请求大小
防止大文件上传攻击:
http { # 客户端请求体最大 10MB client_max_body_size 10m; # 请求头最大 1KB client_header_buffer_size 1k; large_client_header_buffers 4 4k; }2.3 限制访问频率
防止 DDoS 和暴力破解:
http { # 定义限制区域(每秒 10 个请求) limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s; # 定义连接限制区域 limit_conn_zone $binary_remote_addr zone=conn_limit:10m; } server { location /api { # 请求频率限制(允许突发 20 个请求) limit_req zone=api_limit burst=20 nodelay; # 连接数限制(每个 IP 最多 10 个并发连接) limit_conn conn_limit 10; # 超过限制返回 429 limit_req_status 429; limit_conn_status 429; proxy_pass http://localhost:3000; } }2.4 IP 黑白名单
限制特定 IP 访问:
server { location /admin { # 白名单(只允许这些 IP 访问) allow 192.168.1.100; allow 10.0.0.0/8; deny all; proxy_pass http://localhost:3000; } location /api { # 黑名单(禁止这些 IP 访问) deny 192.168.1.200; deny 10.0.0.5; allow all; proxy_pass http://localhost:3000; } }2.5 防止常见攻击
配置安全头信息:
server { # 防止点击劫持 add_header X-Frame-Options "SAMEORIGIN" always; # 防止 MIME 类型嗅探 add_header X-Content-Type-Options "nosniff" always; # 启用 XSS 过滤 add_header X-XSS-Protection "1; mode=block" always; # 严格传输安全(HTTPS) add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; # 内容安全策略 add_header Content-Security-Policy "default-src 'self'" always; # 引用策略 add_header Referrer-Policy "strict-origin-when-cross-origin" always; }💡提示:安全头信息可以防止常见的 Web 攻击,生产环境强烈建议配置。
2.6 CORS 跨域配置
配置跨域资源共享:
server { location /api { # 允许的源 add_header Access-Control-Allow-Origin "https://example.com" always; # 允许的方法 add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS" always; # 允许的头信息 add_header Access-Control-Allow-Headers "Authorization, Content-Type, Accept" always; # 预检请求缓存时间 add_header Access-Control-Max-Age 3600 always; # 处理 OPTIONS 预检请求 if ($request_method = 'OPTIONS') { return 204; } proxy_pass http://localhost:3000; } }3. 日志管理
3.1 访问日志配置
记录客户端访问信息:
http { # 自定义日志格式 log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for" ' '$request_time $upstream_response_time'; # 使用自定义格式 access_log /var/log/nginx/access.log main; }日志字段说明:
| 字段 | 说明 | 示例 |
|---|---|---|
$remote_addr | 客户端 IP | 192.168.1.100 |
$remote_user | 认证用户名 | - |
$time_local | 访问时间 | 04/Sep/2026:10:00:00 +0800 |
$request | 请求行 | GET /api/users HTTP/1.1 |
$status | 响应状态码 | 200 |
$body_bytes_sent | 响应体大小 | 1234 |
$http_referer | 来源页面 | https://example.com |
$http_user_agent | 客户端信息 | Mozilla/5.0… |
$request_time | 请求处理时间 | 0.123 |
$upstream_response_time | 后端响应时间 | 0.100 |
3.2 错误日志配置
记录服务器错误信息:
# 错误日志(级别:debug, info, notice, warn, error, crit, alert, emerg) error_log /var/log/nginx/error.log warn;3.3 按域名分离日志
不同域名使用不同的日志文件:
server { listen 80; server_name example.com; access_log /var/log/nginx/example.com.access.log; error_log /var/log/nginx/example.com.error.log; location / { root /var/www/example.com; index index.html; } } server { listen 80; server_name api.example.com; access_log /var/log/nginx/api.example.com.access.log; error_log /var/log/nginx/api.example.com.error.log; location / { proxy_pass http://localhost:3000; } }3.4 日志轮转配置
使用 logrotate 管理日志文件:
# 创建 logrotate 配置文件sudonano/etc/logrotate.d/nginx/var/log/nginx/*.log { daily # 每天轮转 missingok # 日志文件不存在也不报错 rotate 14 # 保留 14 天的日志 compress # 压缩旧日志 delaycompress # 延迟一天压缩 notifempty # 空文件不轮转 create 0640 www-data adm sharedscripts postrotate # 重新打开日志文件 [ -s /run/nginx.pid ] && kill -USR1 $(cat /run/nginx.pid) endscript }💡提示:日志轮转可以防止日志文件过大,建议生产环境配置。
4. 缓存配置
4.1 代理缓存
缓存后端服务器的响应:
http { # 定义缓存区域 proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=1g inactive=60m use_temp_path=off; server { location /api { # 启用缓存 proxy_cache my_cache; # 缓存状态码 proxy_cache_valid 200 304 10m; proxy_cache_valid 404 1m; # 缓存键 proxy_cache_key $scheme$request_method$host$request_uri; # 添加缓存头 add_header X-Cache-Status $upstream_cache_status; proxy_pass http://localhost:3000; } } }缓存状态说明:
| 状态 | 说明 |
|---|---|
MISS | 缓存未命中,请求后端 |
HIT | 缓存命中,直接返回 |
EXPIRED | 缓存过期,请求后端 |
STALE | 使用过期缓存,同时请求后端 |
UPDATING | 缓存正在更新 |
REVALIDATED | 缓存重新验证成功 |
4.2 缓存清除
手动清除缓存:
http { proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m; server { # 清除缓存接口 location /purge { # 只允许特定 IP 访问 allow 127.0.0.1; deny all; proxy_cache_purge my_cache $scheme$request_method$host$request_uri; } } }💡提示:缓存可以显著提升性能,但需要注意缓存更新策略。
5. WebSocket 代理
5.1 基础 WebSocket 代理
配置 WebSocket 代理,支持实时通信:
map $http_upgrade $connection_upgrade { default upgrade; '' close; } upstream websocket { server 127.0.0.1:3000; } server { listen 80; server_name ws.example.com; location /ws { proxy_pass http://websocket; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; # 超时设置 proxy_read_timeout 86400s; proxy_send_timeout 86400s; } }5.2 WebSocket 负载均衡
配置 WebSocket 负载均衡:
map $http_upgrade $connection_upgrade { default upgrade; '' close; } upstream websocket_backend { ip_hash; # 使用 IP Hash 确保会话固定 server 127.0.0.1:3000; server 127.0.0.1:3001; server 127.0.0.1:3002; } server { listen 80; server_name ws.example.com; location /ws { proxy_pass http://websocket_backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_read_timeout 86400s; proxy_send_timeout 86400s; } }💡提示:WebSocket 负载均衡必须使用
ip_hash或会话保持,否则连接可能断开。
6. 高级负载均衡
6.1 健康检查
Nginx Plus 支持主动健康检查,开源版支持被动健康检查:
upstream backend { server 127.0.0.1:3000 max_fails=3 fail_timeout=30s; server 127.0.0.1:3001 max_fails=3 fail_timeout=30s; server 127.0.0.1:3002 max_fails=3 fail_timeout=30s backup; # 备份服务器 }参数说明:
| 参数 | 说明 | 示例 |
|---|---|---|
max_fails | 最大失败次数 | 3 |
fail_timeout | 失败超时时间 | 30s |
backup | 备份服务器 | 当其他服务器不可用时启用 |
down | 标记服务器不可用 | 用于维护 |
6.2 动态权重调整
根据服务器负载动态调整权重:
upstream backend { server 127.0.0.1:3000 weight=5; server 127.0.0.1:3001 weight=3; server 127.0.0.1:3002 weight=2; }6.3 区域会话保持
使用 cookie 实现会话保持:
upstream backend { server 127.0.0.1:3000; server 127.0.0.1:3001; # 使用 cookie 保持会话 sticky cookie srv_id expires=1h domain=.example.com path=/; }💡提示:会话保持需要 Nginx Plus 或第三方模块,开源版可以使用
ip_hash替代。
7. 实战案例
实战 1:高并发 API 网关
worker_processes auto; worker_cpu_affinity auto; events { worker_connections 4096; use epoll; multi_accept on; } http { include mime.types; default_type application/octet-stream; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; # Gzip 压缩 gzip on; gzip_comp_level 5; gzip_min_length 1k; gzip_types text/plain text/css application/json application/javascript; # 限流配置 limit_req_zone $binary_remote_addr zone=api_limit:10m rate=20r/s; limit_conn_zone $binary_remote_addr zone=conn_limit:10m; # 代理缓存 proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=api_cache:10m max_size=1g inactive=60m; # 后端服务器 upstream api_backend { server 127.0.0.1:3000 max_fails=3 fail_timeout=30s; server 127.0.0.1:3001 max_fails=3 fail_timeout=30s; server 127.0.0.1:3002 max_fails=3 fail_timeout=30s backup; keepalive 32; } # HTTP 重定向到 HTTPS server { listen 80; server_name api.example.com; return 301 https://$host$request_uri; } # HTTPS 服务器 server { listen 443 ssl; server_name api.example.com; ssl_certificate /etc/letsencrypt/live/api.example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/api.example.com/privkey.pem; ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers HIGH:!aNULL:!MD5; # 安全头 add_header X-Frame-Options "SAMEORIGIN" always; add_header X-Content-Type-Options "nosniff" always; add_header X-XSS-Protection "1; mode=block" always; location /api { # 限流 limit_req zone=api_limit burst=50 nodelay; limit_conn conn_limit 20; # 缓存 proxy_cache api_cache; proxy_cache_valid 200 5m; proxy_cache_valid 404 1m; add_header X-Cache-Status $upstream_cache_status; # 代理 proxy_pass http://api_backend; proxy_http_version 1.1; proxy_set_header Connection ""; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } # 日志 access_log /var/log/nginx/api.access.log; error_log /var/log/nginx/api.error.log warn; } }项目知识点:
- 工作进程优化
- Gzip 压缩
- 限流配置
- 代理缓存
- 负载均衡
- 安全配置
实战 2:微服务网关
upstream user_service { server 127.0.0.1:3001; server 127.0.0.1:3002; } upstream order_service { server 127.0.0.1:4001; server 127.0.0.1:4002; } upstream product_service { server 127.0.0.1:5001; server 127.0.0.1:5002; } server { listen 80; server_name gateway.example.com; # 用户服务 location /api/users { proxy_pass http://user_service; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } # 订单服务 location /api/orders { proxy_pass http://order_service; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } # 商品服务 location /api/products { proxy_pass http://product_service; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } }项目知识点:
- 多后端服务配置
- 路径路由
- 负载均衡
实战 3:文件上传服务器
server { listen 80; server_name upload.example.com; client_max_body_size 100m; # 允许最大 100MB 上传 location /upload { # 上传目录 root /var/www/uploads; # 限制上传速度 client_body_rate 1m; # 每秒 1MB # 超时设置 client_body_timeout 120s; client_header_timeout 120s; } location /download { # 下载目录 root /var/www/uploads; # 限速下载 limit_rate 500k; # 每秒 500KB } }项目知识点:
- 大文件上传配置
- 上传/下载限速
- 超时设置
8. 常见问题 FAQ
Q1:如何查看 Nginx 的并发连接数?
A:使用以下命令:
# 查看当前连接数netstat-n|grep:80|wc-l# 查看各状态连接数netstat-n|grep:80|awk'/^tcp/ {++S[$NF]} END {for(a in S) print a, S[a]}'Q2:如何平滑升级 Nginx?
A:按以下步骤操作:
# 1. 备份旧版本cp/usr/sbin/nginx /usr/sbin/nginx.old# 2. 安装新版本# ...# 3. 发送 USR2 信号给主进程kill-USR2$(cat/run/nginx.pid)# 4. 优雅关闭旧工作进程kill-WINCH$(cat/run/nginx.pid.oldbin)Q3:如何配置 HTTP/2?
A:在listen指令中添加http2:
server { listen 443 ssl http2; server_name example.com; ssl_certificate /path/to/cert.pem; ssl_certificate_key /path/to/key.pem; }Q4:如何配置反向代理的超时时间?
A:使用以下指令:
location / { proxy_connect_timeout 60s; # 连接超时 proxy_read_timeout 60s; # 读取超时 proxy_send_timeout 60s; # 发送超时 }Q5:如何配置自定义错误页面?
A:使用error_page指令:
server { error_page 404 /custom-404.html; error_page 500 502 503 504 /custom-50x.html; location = /custom-404.html { root /var/www/errors; internal; } location = /custom-50x.html { root /var/www/errors; internal; } }9. 学习资源与建议
学习建议
1.先掌握基础,再学习进阶:确保理解基础配置后再学习进阶特性
2.多查看官方文档:官方文档是最权威的资料
3.善用测试命令:每次修改配置后,先用nginx -t测试语法
4.查看日志排错:遇到问题时,查看错误日志是最快的排错方法
5.使用版本控制:配置文件使用 Git 管理,方便回滚和对比
官方资源
- Nginx 官方文档
- Nginx 模块文档
- Nginx 博客
- Nginx GitHub
推荐工具
- SSL Labs - SSL 配置测试
- GTmetrix - 网站性能测试
- WebPageTest - 网站性能分析
- curl - HTTP 请求测试