SPA刷新404的主因是try_files配置位置错误:必须将root置于try_files之前,且API接口需用location /api/(带尾斜杠)严格匹配,避免被根location误捕获。
配置位置不对,是导致 SPA 刷新 404 的最常见原因。它不是加了就完事,而是必须放在能覆盖全部
前端
路由
、又不干扰 API 请求的 location 块里。
location / 的 try_files 必须放在 root 之后
很多人把
放在
前面,比如:
这会导致 Nginx 在解析
时找不到实际文件路径,因为
还没生效。Nginx 查找文件会失败,直接跳到
,但此时
已设,所以它去找
—— 看似没问题,实则埋雷:一旦你有多个 location 或 alias 混用,路径拼接就会错乱。
正确顺序是:
必须在
之前声明
指令可选,但建议显式写上
中的
是绝对路径(相对于
),不是 URL 路径
API 接口 location 必须严格前缀匹配且带尾部斜杠
如果
里写了
,而你又同时配了
,Nginx 会按最长前缀匹配——
先命中
,再走
,最终被重写成
,API 请求就丢了。
立即学习
“
前端免费学习笔记(深入)
”;
解决方法只有两个硬性条件:
块必须写成
(末尾带
)
后端地址也必须以
结尾,如
不能写成
(无尾斜杠),否则 Nginx 会把
当作
代理出去,后端收不到原始路径
history 模式下不能用 alias 替代 root
有人图省事,在
里用
指向 dist 目录:
面向设计的AXUI前端框架表单
面向设计的AXUI前端框架表单是一款包含表格、列表、弹窗等的AXUI前端框架表单下载。
下载
这会导致
中的
被解析为
(双斜杠),或根本找不到——
不支持
这种根路径回退,它只做路径替换,不参与 root 上下文。
必须用
:
(注意:不带末尾斜杠)
配合
才能正确 fallback
如果非要用
,只能针对子路径,比如
,且
不能出现在该块里
刷新 404 时先看 error.log 里的 real path
Nginx 的
里有一行关键信息:
。这个
就是它真正去磁盘找的路径。
对照你的配置,检查三件事:
日志里显示的路径,是否和你
指向的目录一致?
路径末尾是不是多了一个
?说明用了
或
多写了斜杠
请求的 URI 是
,但日志里查的是
?说明
触发了目录查找,得确认该路径下真有
(SPA 不该有)
真正可靠的 fallback 只有一条:当
和
都不存在时,才交由
处理。任何中间环节的路径错位,都会让这个链条断裂。
try_filestry_filesrootlocation / {
try_files $uri $uri/ /index.html;
root /usr/share/nginx/html;
}$uriroot/index.htmlroot/usr/share/nginx/html/index.htmlroottry_filesindexindex index.html;try_files $uri $uri/ /index.html;/index.htmlrootlocation /try_fileslocation /api/api/users/try_files/index.htmllocationlocation /api//proxy_pass/proxy_pass http://backend/;location /api/api/users/userslocation /aliaslocation / {
alias /var/www/myapp/dist/;
}try_files $uri $uri/ /index.html/index.html/var/www/myapp/dist//index.htmlalias/index.htmlrootroot /var/www/myapp/dist;try_files $uri $uri/ /index.html;aliaslocation /static/try_fileserror.logopen() "/xxx/xxx" failed (2: No such file or directory)/xxx/xxxroot/aliasroot/product/123/product/123/index.html$uri/index.html$uri$uri//index.html