Nginx 专题 · 第 16 / 17 章
16速查表与高频坑
tools/verify-behavior.js 在
nginx/1.27.5(官方 nginx:1.27-alpine 镜像)上的运行结果,可以自己复现。
16.1 命令与信号速查
nginx 的命令行只有十来个开关,但每一个都很关键。特别注意
-t 与 -T 的区别:前者只校验语法,后者把生效的完整配置打印出来
(含所有 include 展开后的内容),是排查「配置到底加载了没有」最快的工具。
| 命令 | 作用 | 什么时候用 |
|---|---|---|
nginx -t | 校验语法与文件是否存在,打印配置文件路径 | 每次改配置后、reload 前 |
nginx -tq | 同上,通过时不输出 | 写进发布脚本 |
nginx -T | 打印生效的完整配置(include 已展开) | 排查继承、确认加载了哪个文件 |
nginx -v / -V | 版本 / 版本 + 编译参数 | 确认模块有没有编进去(「指令不认识」头号原因) |
nginx -s reload | 平滑重载配置 | 发布、改配置(不断已有连接) |
nginx -s reopen | 重新打开日志文件 | 日志切割之后 |
nginx -s quit / stop | 优雅退出 / 快速退出 | 停机维护 / 紧急停止 |
nginx -c 文件 -p 前缀 | 指定配置文件与 prefix | 一台机器跑多套 nginx 实例 |
nginx -g "daemon off;" | 临时追加全局指令 | 容器里前台运行 |
不给二进制发命令而是发信号时,行为如下(kill -信号 $(cat /var/run/nginx.pid))。
这张表值得记住,因为「升级、切日志、下线 worker」全靠它:
| 信号 | 行为 | 典型用途 |
|---|---|---|
HUP | 重新加载配置,启动新 worker、优雅关闭旧 worker | 等价于 -s reload |
USR1 | 重新打开日志文件(master 与 worker 都重开) | logrotate 之后必须发它,否则日志继续写进已被 rename 的旧 inode |
USR2 | 平滑升级:启动新的 master + worker(新二进制) | 换 nginx 版本的第一步 |
WINCH | 优雅关闭所有 worker(master 不动) | 平滑升级的第二步 |
QUIT | 优雅退出 | 处理完存量请求再退出 |
TERM / INT | 立即退出 | 只在紧急情况下用 |
$ nginx -t && nginx -s reload # 改配置的标准动作,顺序不能反 $ kill -USR1 $(cat /var/run/nginx.pid) # 切完日志后通知重开 $ nginx -V 2>&1 | tr ' ' '\n' | grep with- # 看编进去的模块 $ nginx -T | grep -n "add_header" # 看生效配置里到底有哪些响应头
16.2 配置片段速查
下面这些片段可以直接抄。抄之前记住三条容易翻车的规则:
① proxy_pass 结尾带不带 / 会改变路径拼接方式;
② add_header 与 proxy_set_header 是数组型指令,子级写了就整组替换父级;
③ add_header 默认只管 2xx/3xx,错误响应上要加 always。
server {
listen 80;
server_name app.example.com;
root /var/www/app;
index index.html;
# 带 hash 的构建产物:一年不可变缓存
location ^~ /assets/ {
expires 1y;
add_header Cache-Control "public, max-age=31536000, immutable" always;
access_log off;
}
# 入口文件绝不能缓存,否则发版后用户还看旧页面
location = /index.html {
add_header Cache-Control "no-cache" always;
}
# 前端路由兜底
location / {
try_files $uri $uri/ /index.html;
}
}
location /api/ {
# 结尾的 / 会把 /api/ 前缀替换掉;不要替换就写成 proxy_pass http://backend;
proxy_pass http://backend/;
proxy_http_version 1.1;
proxy_set_header Host $host; # 默认是 $proxy_host,后端会看到上游地址
proxy_set_header X-Real-IP $remote_addr; # 默认不发
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Connection ""; # 配合 upstream keepalive 复用连接
proxy_connect_timeout 3s;
proxy_send_timeout 30s;
proxy_read_timeout 30s; # 长任务要单独调大,否则 504
proxy_next_upstream error timeout http_502 http_503 http_504;
}
server {
listen 443 ssl;
http2 on; # 1.25.1 之后的新写法
server_name app.example.com;
ssl_certificate /etc/nginx/ssl/fullchain.pem; # 站点证书在前,中间证书在后
ssl_certificate_key /etc/nginx/ssl/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305;
ssl_prefer_server_ciphers off; # TLS 1.3 的套件由 nginx 固定,这条对它无效
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
ssl_session_tickets off; # 开 = 换取性能,代价是前向安全性
ssl_stapling on;
ssl_stapling_verify on;
ssl_trusted_certificate /etc/nginx/ssl/chain.pem;
add_header Strict-Transport-Security "max-age=31536000" always;
}
server { # 80 端口只做跳转,且用相对跳转
listen 80;
server_name app.example.com;
return 301 https://$host$request_uri; # 显式拼 $request_uri,否则查询串会丢
}
http {
# 定义型指令只能在 http 层
limit_req_zone $binary_remote_addr zone=perip:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=login:10m rate=1r/s;
limit_conn_zone $binary_remote_addr zone=connip:10m;
server {
# 登录接口:严格限流
location = /api/login {
limit_req zone=login burst=3 nodelay;
limit_req_status 429;
proxy_pass http://backend;
}
# 普通接口:宽松限流 + 限连
location /api/ {
limit_req zone=perip burst=50 nodelay;
limit_conn connip 50;
proxy_pass http://backend;
}
# ★ 千万不要在上面这些 location 里再写 return(会短路掉限流,见 10.4)
}
}
http {
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=api_cache:10m
max_size=2g inactive=60m use_temp_path=off;
log_format json escape=json '{"time":"$time_iso8601","ip":"$remote_addr",'
'"method":"$request_method","uri":"$request_uri","status":$status,'
'"rt":$request_time,"urt":"$upstream_response_time","ua":"$http_user_agent",'
'"upstream":"$upstream_addr","cache":"$upstream_cache_status"}';
server {
access_log /var/log/nginx/access.log json;
location /api/ {
proxy_pass http://backend;
proxy_cache api_cache;
proxy_cache_key "$scheme$request_method$host$request_uri"; # 显式带上 method 与 host
proxy_cache_valid 200 10s;
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
proxy_cache_background_update on;
add_header X-Cache-Status $upstream_cache_status always; # 排查命中率最有用
}
}
}
location /ws/ {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade; # WebSocket 必须
proxy_set_header Connection "upgrade";
proxy_read_timeout 3600s; # 长连接别用默认 60s
proxy_buffering off; # SSE / 流式响应要关缓冲
}
16.3 常用变量速查
变量在被使用时才求值且大多是只读的。日常 90% 的场景只会用到下面这些。
最容易搞错的是 $uri 与 $request_uri:前者经过了解码与归一化,
后者是客户端发来的原始串。
| 变量 | 含义 | 注意 |
|---|---|---|
$uri | 当前请求的路径,已解码、已归一化 | 做白名单/签名校验用它(绕不过去) |
$request_uri | 客户端发来的原始路径 + 查询串 | 记日志、排查客户端到底发了什么用它 |
$args / $arg_name | 完整查询串 / 某个具体参数 | $arg_x 未传时为空串,不区分「没传」与「空值」 |
$host / $http_host | 请求的域名 / 原始 Host 头 | $host 已归一化(小写、去端口),适合做拼装 |
$remote_addr | 直连 nginx 的客户端 IP | 前面还有代理时这是代理的 IP,要配 realip 才是真实 IP |
$proxy_add_x_forwarded_for | 原有 XFF + $remote_addr | 拼 XFF 头的标准写法 |
$scheme | http 或 https | 透传给后端判断协议 |
$request_time | 从收到首字节到发完响应的总耗时 | 用户实际感知的耗时 |
$upstream_response_time | 后端响应耗时(多台时逗号分隔) | 与 $request_time 一比就知道慢在 nginx 还是后端 |
$upstream_addr | 实际转到的后端地址 | 502/504 排障时第一眼要看它 |
$upstream_cache_status | 缓存结果:HIT/MISS/BYPASS/EXPIRED/STALE/UPDATING | 算命中率、验证缓存是否生效 |
$status / $body_bytes_sent | 响应码 / 发出字节数 | 日志与告警的基础字段 |
$ssl_protocol / $ssl_cipher | 本次连接用的 TLS 版本与套件 | 验证「客户端到底协商到了 TLS 1.2 还是 1.3」 |
用户说「接口慢」时,先看 $request_time 与 $upstream_response_time:
两者接近→ 慢在后端;前者远大于后者→ 慢在 nginx 到大客户端这一段
(常见原因:客户端网络差、gzip 压大响应、proxy_buffering off 边收边发)。
只看总耗时是分不清这两者的。
16.4 状态码速查与归因
看到状态码先别改配置,先确认这个码是谁产生的:nginx 自己、上游, 还是客户端主动断开。下面这张表按「谁的问题」分组。
| 码 | 谁产生的 | 常见根因 | 先查什么 |
|---|---|---|---|
| 499 | nginx 记录,客户端主动断开 | 客户端超时先走了(移动网络弱、上游太慢、超时配得太长) | $request_time 与上游耗时;上游是不是超过客户端耐心 |
| 502 | nginx 产生 | 连不上上游 / 上游发了非法响应 / 上游过早关闭连接 | $upstream_addr、error.log 的 connect() failed 或 upstream prematurely closed |
| 503 | 可能是 nginx 也可能是上游 | 限流被拒(limit_req)、上游全部不可用、上游自己返回 503 |
error.log 里的 limiting requests;上游健康状态 |
| 504 | nginx 产生 | 上游在 proxy_read_timeout 内没返回 |
上游自身耗时;是不是把长任务也套用了默认 60s 超时 |
| 413 | nginx 产生 | 请求体超过 client_max_body_size(默认仅 1m) |
上传接口有没有单独调大该值 |
| 400 | nginx 产生 | 请求头/请求行非法、Host 缺失、请求头过大 |
error.log 中 client sent invalid ... |
| 403 | nginx 或上游 | 文件权限不对、deny 命中、目录无索引且未开 autoindex |
error.log 的 access forbidden / Permission denied |
| 404 | nginx 或上游 | root/alias 路径算错、try_files 兜底写错、上游路由不匹配 |
error.log 里的实际磁盘路径 |
| 444 | nginx 特有 | 配置里主动 return 444(不响应直接断连) |
是不是兜底 server 拦到了正常请求 |
| 301 / 302 | nginx 或上游 | 跳转配置;注意 return 301 会丢查询串 |
响应头 Location 是不是拼成了 http://127.0.0.1/... |
16.5 20 个高频坑
这 20 条按「踩到的频率」排序,前 8 条在 总目录里也单独列了一次。 每条都给出现象 → 原因 → 解决,可以直接当排查清单用。
| # | 现象 | 原因 | 解决 |
|---|---|---|---|
| 1 | 代理后后端 404,路径多/少一层 | proxy_pass 结尾带 URI 时 location 前缀会被替换 | 要透传就不写 URI;要替换就写成 proxy_pass http://backend/;,并让后端打印 $uri 确认 |
| 2 | 后端拿到的客户端 IP 全是 nginx 的 | 默认不发 XFF / X-Real-IP;后端也没解析 | nginx 侧配 proxy_set_header X-Forwarded-For ...,后端侧启用 forward-headers 解析 |
| 3 | 后端虚拟主机路由错、回调域名不对 | 默认 Host 是 $proxy_host(上游地址) | proxy_set_header Host $host; |
| 4 | 在 location 里加了一个 add_header,别的头全没了 | 数组型指令整组替换,不合并继承 | 抽成 include snippets/xxx.conf,每个 location 都 include |
| 5 | 404 / 502 响应上没有安全头 | add_header 默认只对 2xx/3xx 生效 | 每条都加 always |
| 6 | 重定向跳到 http://127.0.0.1/... 且丢了参数 | return 301 丢掉原始查询串;默认 absolute_redirect on,端口取 nginx 自己的 listen 端口 | 自己拼 $request_uri;代理后面加 absolute_redirect off; |
| 7 | 限流「配了但没生效」 | 同一个 location 里写了 return,它在 rewrite 阶段就终结了请求 | 把 limit_req 放到另一个不带 return 的 location |
| 8 | deny all 挡不住 | 同上,return 绕过了 access 阶段 | 不要和 return 同 location;或用 error_page 组织 |
| 9 | 改完配置 reload 后行为没变 | 改的文件没被 include 到;或 -t 失败后 nginx 继续用旧配置 | nginx -T 确认生效内容;固定用 nginx -t && nginx -s reload |
| 10 | 日志切割后磁盘还是满的 | 只 rename 了文件,worker 还拿着旧 fd 在写 | 切割后发 kill -USR1(或 nginx -s reopen) |
| 11 | 大文件上传报 413 | client_max_body_size 默认仅 1m | 给上传 location 单独调大,并检查 client_body_temp_path 所在分区空间 |
| 12 | 接口偶发 504,后端日志显示处理很快 | proxy_read_timeout 默认 60s,长任务/队列阻塞导致超时;或上游连接池被占满 | 长任务单独调大超时;配 upstream keepalive + proxy_http_version 1.1 |
| 13 | WebSocket 连上就断 | 没配 Upgrade/Connection 头,或 proxy_read_timeout 太短 | 三条一起配:proxy_http_version 1.1、两个头、调大 read timeout |
| 14 | SSE / 流式响应被「憋住」不输出 | nginx 默认缓冲上游响应 | proxy_buffering off;(必要时加 X-Accel-Buffering: no) |
| 15 | 只有一台后端一直被打 | ip_hash 在 NAT/办公网出口后按 IP 哈希导致倾斜 | 换 least_conn 或一致性 hash $key consistent;或改用共享会话 + 轮询 |
| 16 | 某台后端挂了但流量还打过去 | 默认只做被动检查,且 proxy_next_upstream 默认不含 http_502 | 补 http_502/503/504;开源版没有主动健康检查,需外部探活摘节点 |
| 17 | 发了新版,用户还看到旧页面 | index.html 被缓存了 | 入口文件配 Cache-Control: no-cache;静态产物用 hash 文件名 + 一年 immutable |
| 18 | 缓存命中率极低 | cache key 带了随机/时间参数,或响应有 Set-Cookie / Cache-Control: private | 显式定义 proxy_cache_key;用 $upstream_cache_status 定位是 MISS/BYPASS 还是 EXPIRED |
| 19 | 直接用 IP 访问看到了内部站点 | 没指定 default_server,第一个 server 成了兜底 | 加一个 listen 80 default_server; return 444; 的兜底 server |
| 20 | unknown directive 但指令名明明没错 | 该模块没编译进当前 nginx | nginx -V 看编译参数;官方镜像的 --with-* 列表见 16.7 |
16.6 一条命令排障表
值班时最怕「不知道从哪下手」。这张表把常见症状直接映射到一条命令,
并说明该看输出里的哪个字段。前提是你知道 nginx 的访问日志格式里有
$upstream_addr 与 $upstream_response_time
(默认 combined 格式里没有,需要自己加,见 第 12 章)。
| 症状 | 一条命令 | 看什么 |
|---|---|---|
| 想知道现在谁在连、连了多少 | ss -s && ss -lntp | grep nginx |
ESTAB 数量、Send-Q 是否堆积(堆积=应用没及时读) |
| 502 到底连没连上后端 | tail -200 error.log | grep -E "connect\(\) failed|upstream" |
connect() failed (111: Connection refused) =后端没监听;110: timeout =网络/防火墙 |
| 504 是 nginx 慢还是后端慢 | awk '{print $NF}' access.log | sort | uniq -c | sort -rn | head |
配合 $upstream_response_time 字段比较 |
| 502 集中在某一台后端 | grep " 502 " access.log | grep -oE 'upstream=[^ ]+' | sort | uniq -c |
哪个 $upstream_addr 占比最高 |
| 限流到底有没有生效 | grep "limiting requests" error.log | tail |
有记录=真的拦了;没记录且 503=0,说明限流没跑到(见坑 7/8) |
| 缓存有没有命中 | grep -oE '"cache":"[A-Z]+"' access.log | sort | uniq -c |
HIT 占比;大量 BYPASS 要看 proxy_cache_bypass |
| 配置里到底有哪些 add_header | nginx -T | grep -n add_header |
看有没有哪一层把父级覆盖掉了 |
| 某个域名被哪个 server 处理了 | nginx -T | grep -nE "server_name|listen" |
确认有没有 default_server 抢答 |
| 打开的文件句柄是不是到顶了 | ls /proc/$(cat /var/run/nginx.pid)/fd | wc -l |
与 worker_rlimit_nofile、ulimit -n 对比 |
| TLS 协商到了哪个版本 | openssl s_client -connect app.example.com:443 -servername app.example.com </dev/null 2>/dev/null | grep -E "Protocol|Cipher" |
确认客户端实际用的是 TLS 1.2 还是 1.3 |
上面好几条依赖 $upstream_addr、$upstream_response_time、
$upstream_cache_status 这些字段。如果还在用 nginx 默认的
combined 格式,这些信息根本没有被记下来,
出问题时只能靠猜。把日志格式补齐是投入产出比最高的一次改动,见
第 12 章。
16.7 默认值速查(附实测)
nginx 的默认值决定了「什么都不配的时候会发生什么」,而大部分线上事故恰恰发生在 「什么都没配」的地方。下表右侧的「实测」列标明了验证方式, 带「实测」的结果来自 nginx/1.27.5 上真实运行,可以直接复现。
| 指令 | 默认值 | 你没配它时会怎样 | 实测 |
|---|---|---|---|
gzip | off | 客户端发了 Accept-Encoding: gzip 也不会压缩,响应体积白白变大 |
实测:带 gzip 声明请求静态文件,响应无 Content-Encoding |
client_max_body_size | 1m | 超过 1MB 的上传直接被拒,前端只看到 413 | 实测:POST 2MB 请求体 → 413 |
server_tokens | on | 响应头暴露精确版本号,方便攻击者按版本找漏洞 | 实测:Server: nginx/1.27.5 |
proxy_http_version | 1.0 | 回源用 HTTP/1.0,无法复用长连接(upstream keepalive 形同虚设) | 实测:后端 $server_protocol = HTTP/1.0 |
proxy_set_header Host | $proxy_host | 后端看到的域名是上游地址(如 127.0.0.1:8080),虚拟主机/回调域名全错 |
实测:后端 $http_host = 127.0.0.1:8082 |
X-Forwarded-For / X-Real-IP | 不发送 | 后端拿不到真实客户端 IP,风控、审计、限流全失效 | 实测:后端看到 xff=[] realip=[] |
proxy_next_upstream | error timeout | 后端返回 502/503/504 时不会自动换一台后端,错误直接给用户 | 官方文档;默认不含 http_5xx |
add_header 的生效范围 | 仅 2xx / 3xx | 404、403、502 等错误响应上你的安全头全都不在 | 实测:404 上 X-Loc 与 X-Server 都没有;加 always 后才有 |
add_header 的继承 | 不合并 | 子级写一个头,父级全部头失效 | 实测:location 内加 X-Loc 后 server 级 X-Server 消失 |
merge_slashes | on | //a 与 /a 被视为同一路径(通常是你想要的,但做签名校验时要意识到) |
实测:/v//vars 的 $uri = /v/vars |
absolute_redirect | on | 跳转的 Location 被补成绝对地址,端口取 nginx 自己的 listen 端口——在代理/容器后面会跳到错地址 |
实测:return 301 /r/dest → Location: http://127.0.0.1/r/dest |
return 301 与查询串 | 丢弃 | 跳转后原始查询参数丢失,登录回跳、UTM 参数全没了 | 实测:请求 /r/ret?x=1 → Location 不含 x=1 |
keepalive_timeout | 编译默认 75s;官方镜像的 nginx.conf 显式设为 65s |
连接空闲保持时间;过长会占着 worker 连接数不放 | 实测:nginx -T 中为 keepalive_timeout 65; |
worker_processes | 编译默认 1;官方镜像设为 auto | 只用一个核,多核机器白买 | 实测:nginx -T 中为 worker_processes auto; |
worker_connections | 1024 | 单 worker 连接数上限;作为反向代理时每条客户端连接还会占一条到上游的连接 | 实测:nginx -T 中为 worker_connections 1024; |
| 官方镜像的管理员目录 | user nginx; | worker 以 nginx 用户运行;静态文件权限要允许该用户读 | 实测:nginx -T 中为 user nginx; |
| 日志文件位置 | 软链到 /dev/stdout、/dev/stderr | 容器里读 /var/log/nginx/*.log 读不到内容,要用 docker logs |
实测:readlink -f /var/log/nginx/error.log 指向管道而非普通文件 |
上面标「实测」的每一条,都能用仓库里的脚本一条命令重跑。
它会在容器里注入一份专门覆盖这些行为的配置,逐条比对状态码、响应头、响应体,
并把 error.log 里「谁真的被限流、谁真的被拒绝」的记录一起打出来:
$ cd knowledge/nginx $ node tools/verify-behavior.js # 需要本机有可用的 Docker # 输出 38 条 ✓,退出码 0;任何一条与文档不符会打印差异并以 1 退出
这样做的好处是:结论不会随着时间腐坏。以后升级 nginx 版本时重跑一次, 就能知道有没有行为发生变化——这比「记得当年是这么配的」可靠得多。
16.8 接下来怎么走
速查表能救急,但救不了「不知道为什么」。如果上面有哪一条你只能背结论、 说不出原因,建议顺着链接回去读对应章节:location 与继承去 第 3 章,代理语义去 第 6 章, 限流与访问控制的实测细节去 第 10 章, 状态码排障剧本去 第 14 章。
想检验自己是不是真的掌握了,直接做 第 17 章 的自测题——那里有 40 道题,答不上来的题会明确指向该回哪一章。