Nginx多级子目录404本质是uri归一化与root/alias拼接顺序不匹配:$uri已归一化,root追加、alias替换,try_files各选项按此规则展开,fallback URI会触发内部重定向并重新匹配location。

当 try_files 在多级子目录(如 /a/b/c/)中出现 404 或路径错配,本质是 Nginx 对 uri 的截断逻辑与 root/alias 的拼接规则不匹配导致的——不是配置写错了,而是没看清 URI 归一化和路径拼接发生的先后顺序。
确认当前请求 URI 和 location 匹配结果
Nginx 所有路径处理都基于 已归一化后的 $uri 变量(不含查询参数、已解码、无重复斜杠、结尾斜杠保留)。用 log_format 把关键变量打出来:
log_format debug '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'uri:"$uri" request_uri:"$request_uri" '
'document_root:"$document_root" '
'script_filename:"$script_filename"';
重点比对:$uri(实际参与 try_files 拼接的值)、$request_uri(原始请求)、$document_root(最终 root 路径)。常见偏移根源:location 使用正则或前缀匹配时,$uri 被截断但未显式重写,导致后续拼接起点错误。
区分 root 和 alias 的拼接行为差异
root 是“追加”模式:
- location /a/b/ { root /var/www; }
- 请求 /a/b/c/file.js → $uri = /a/b/c/file.js → 拼成 /var/www/a/b/c/file.js
alias 是“替换”模式:
- location /a/b/ { alias /var/www/x/; }
- 请求 /a/b/c/file.js → $uri = /a/b/c/file.js → 替换 /a/b/ 后得 /var/www/x/c/file.js
⚠️ 多级嵌套时最容易踩坑:用 alias 却没对齐 location 末尾斜杠;或在 root 下误以为 location 前缀会被自动剥离。
检查 try_files 中每个候选路径的展开逻辑
try_files 每一项都是相对 root 或 alias 的路径,且不经过 location 重写。例如:
location /app/ {
root /data;
try_files $uri $uri/ /app/index.html;
}
请求 /app/sub/dir/page.html 时:
- $uri = /app/sub/dir/page.html
- 第一项 $uri → 拼为 /data/app/sub/dir/page.html
- 第二项 $uri/ → 拼为 /data/app/sub/dir/page.html/(注意末尾斜杠!这会变成目录访问)
- 第三项 /app/index.html → 拼为 /data/app/index.html(因为是绝对路径,直接加 root)
常见故障点:
- 用 alias 时第三项写了 /app/index.html,但 alias 不处理绝对路径开头的 /,导致拼成 /var/www/x//app/index.html
- 想 fallback 到根目录下的 index,却写了 /index.html(被当成相对于 root 的绝对路径),应改用 index.html(相对路径)或显式指定 /var/www/index.html
用 internal 重定向验证 fallback 是否真正触发
如果 try_files 最后一项是 URI(如 /fallback.html),Nginx 会发起内部重定向 —— 此时该 URI 会重新进入 location 匹配流程。这意味着:
- 它可能匹配到另一个 location 块,触发新的 root/alias 规则
- 若没匹配到任何 location,就报 404(即使文件物理存在)
排查方法:
- 在 fallback URI 对应的 location 块里加 return 200 "hit fallback";
- 或用 error_log notice; 配合 log_not_found on; 查看哪一步 missing


















