Nginx 上线前检查清单
新服务上线前,很多人会检查代码能不能跑、接口能不能通、数据库能不能连, 但 Nginx 这一层经常被忽略。以下 7 项过一遍,大部分上线事故可以提前避免。
检查清单
① 真实 IP(set_real_ip_from)
服务前面有 CDN / 负载均衡时,Nginx 拿到的 $remote_addr 是代理 IP。
必须用 set_real_ip_from + real_ip_header 恢复真实 IP。
set_real_ip_from 10.0.0.0/8;
set_real_ip_from 172.16.0.0/12;
set_real_ip_from 192.168.0.0/16;
real_ip_header X-Forwarded-For;
real_ip_recursive on;
陷阱: 不要写 set_real_ip_from 0.0.0.0/0,否则攻击者可伪造 X-Forwarded-For。
详细踩坑参见 nginx-config-pitfalls 的踩坑点十一。
② 核心接口限流(limit_req_zone)
登录、验证码、上传、搜索、下单等接口必须按场景单独限流:
limit_req_zone $binary_remote_addr zone=login_limit:10m rate=5r/m;
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
server {
location /api/login { limit_req zone=login_limit burst=3 nodelay; ... }
location /api/ { limit_req zone=api_limit burst=20 nodelay; ... }
}
参见 nginx-config-pitfalls 踩坑点十二。
③ 超时参数按接口拆分
# 普通接口
location /api/ {
proxy_connect_timeout 3s;
proxy_send_timeout 10s;
proxy_read_timeout 30s;
}
# 长任务单独拆开
location /api/export/ {
proxy_read_timeout 180s;
}
④ 上传大小(client_max_body_size)
不上传的接口保持默认,上传接口单独放宽:
server {
client_max_body_size 10m;
location /api/upload/video {
client_max_body_size 200m;
}
}
不要全局 1024m。 参见 nginx-config-pitfalls 踩坑点五。
⑤ 静态资源缓存策略
| 文件名特征 | 缓存策略 |
|---|---|
带 hash(app.8f3a1c.js) |
expires 30d; add_header Cache-Control "public, immutable"; |
| 不带 hash | expires 7d; add_header Cache-Control "public"; |
| HTML 入口文件 | 不建议强缓存 |
⑥ 日志字段包含 upstream 信息
log_format main '$remote_addr - $request '
'status=$status body_bytes_sent=$body_bytes_sent '
'request_time=$request_time '
'upstream_addr=$upstream_addr '
'upstream_status=$upstream_status '
'upstream_response_time=$upstream_response_time '
'xff=$http_x_forwarded_for';
access_log /var/log/nginx/access.log main;
参见 nginx-config-pitfalls 踩坑点九。
⑦ 配置测试和回滚
# 改前备份
cp /etc/nginx/conf.d/app.conf{,.bak.$(date +%F-%H%M)}
# 测试 + 平滑加载
nginx -t && systemctl reload nginx
不要 restart 替代 reload。 回滚命令提前写在发布工单里。
场景优先级速查
| 场景 | 优先检查的 3 项 |
|---|---|
| 面向公网的 API 服务 | 真实 IP / 限流 / 超时参数 |
| 管理后台 | 真实 IP / 限流 / 测试和回滚 |
| 静态资源站点 | 静态缓存 / 日志字段 / 上传大小 |
| 有 CDN 的前端应用 | 真实 IP / 静态缓存 / 日志字段 |
| 内部小工具 | 上传大小 / 超时参数 / 测试和回滚 |
关联页面
| 页面 | 关联点 |
|---|---|
| nginx-realtime-push-guide | SSE/WebSocket 实时推送 — 上线前超时/缓冲/会话保持检查 |
| nginx-load-balancing-strategy-guide | Nginx 负载均衡策略选择实战指南 — 加权轮询与 IP Hash 深度对比、混合策略最佳实践 |
| nginx-log-analysis-monitoring-guide | Nginx 日志分析与监控体系构建指南 — 自定义日志格式、性能分析技巧、GoAccess 可视化、 |
| keepalived-ha-hidden-pitfalls | Keepalived+Nginx 高可用架构 3 个隐藏坑位与生产级防护方案(脑裂/健康检查僵尸进程 |
| rate-limiting-algorithms | 接口限流 5 种算法详解(限流配置的算法原理参考) |