跳转到主内容
websoft网络软件专家 - 深耕网络技术,打造实用软件!

如何配置 Nginx 解决 SPA 应用前端路由刷新后由于 Location 匹配不当出现的 404

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

相关文章