nginx路由与重写排查手册:①location匹配严格按优先级:=(精确)>^~(最长前缀)>~ / ~*(正则,自上而下首中即停)>/(通用);②rewrite在location匹配后执行,flag决定走向:permanent/redirect立即返回,last触发uri重匹配,break终止本location内后续rewrite;③spa必须用try_files $uri $uri/ /index.html于根location,禁放子路径;④实操验证:curl测试return响应、nginx -t查配置、rewrite_log+error_log跟踪重写过程。

直接输出标准化的 Nginx 路由与重写规则排查手册,核心是聚焦 location 匹配逻辑、rewrite 执行顺序、常见陷阱及可验证的检查步骤,不堆砌理论,只留能动手的要点。
location 匹配优先级必须理清
Nginx 不是按配置顺序匹配,而是严格遵循以下优先级:
- 精确匹配(=)最高,如
location = /api只匹配/api,不带尾部斜杠也不行 - 正则匹配(~ 或 ~*)次之,且按配置文件中出现顺序从上到下扫描,第一个命中即停
- 最长前缀匹配(无修饰符或 ^~)最后,比如
location /admin/和location /admin/users同时存在,后者更长,会优先生效
验证方法:在对应 location 块中临时加 return 200 "matched: /admin/users";,用 curl 测试真实路径,看返回内容是否符合预期。
rewrite 指令执行时机与 flag 影响结果
rewrite 不是“改完就发”,它发生在 location 匹配之后、实际处理之前,且 flag 决定后续流程:
- permanent 或 redirect:立即返回 301/302,浏览器跳转,不再走后续 location
- last:重写 URI 后,放弃当前 location,重新从 server 级开始匹配新 URI(相当于内部重定向)
- break:重写 URI 后,停止本 location 内所有 rewrite,继续执行本 location 下的其他指令(如 proxy_pass)
典型误配:在 location /old/ 中写 rewrite ^/old/(.*)$ /new/$1 last;,但没配 location /new/,结果 404 —— 因为 last 触发了新匹配,而 /new/ 路径未定义处理逻辑。
路由回退(SPA 应用)必须靠 try_files
Vue/React 等前端路由使用 history 模式时,刷新子页面(如 /user/profile)会触发 Nginx 查找物理文件,找不到就 404。正确解法不是靠 rewrite,而是:
- 在根 location 中用
try_files $uri $uri/ /index.html; - 确保
/index.html是你的 SPA 入口,并放在 root 指向的目录下 - 避免把 try_files 放在子 location(如
location /api/)里,否则 API 请求也可能被错误兜底到 index.html
验证:curl -I http://your-domain.com/nonexistent-path,响应应为 200(内容是 index.html),而非 404。
调试重写过程的三个实操命令
不用猜,用工具看 Nginx 实际怎么走的:
- 检查语法并测试重写:
nginx -t && nginx -T 2>/dev/null | grep -A5 -B5 "rewrite\|location",确认配置已加载且结构清晰 - 开启重写日志(临时):
rewrite_log on;+error_log /var/log/nginx/rewrite.log notice;,然后tail -f /var/log/nginx/rewrite.log查看每次请求的 rewrite 步骤 - 模拟请求路径匹配:
nginx -T | awk '/location/,/}/' | grep -E "(location|return|proxy_pass|rewrite)",快速定位目标块中的关键行为











