vue/react 刷新 404 的“完美适配”需三点:root 指向真实 dist 目录;子路径部署时 alias 与 publicpath 一致且 try_files 兜底带前缀;api 请求须单独 location /api/ 拦截,避免被 try_files 误处理。

直接用 try_files $uri $uri/ /index.html 就能解决 Vue/React 刷新 404,但“完美适配”关键在三点:路径对得准、静态资源走得到、非页面请求不误伤。
root 路径必须指向真实 dist 目录
如果构建产物放在 /var/www/my-app/dist,Nginx 的 root 就得写成:
-
root /var/www/my-app/dist;(注意不是/dist/结尾) - 不能写成
root /var/www/my-app;然后靠location / { try_files ... }硬扛——那样$uri匹配的是/var/www/my-app/user/123,根本找不到文件 - 验证方法:访问
https://yoursite.com/js/app.xxx.js,能正常加载 JS 就说明$uri分支生效了
子路径部署时,兜底路径要带前缀
项目部署在 https://example.com/admin/,前端配置(如 vue.config.js 中 publicPath: '/admin/')和 Nginx 必须同步:
- 用
alias更稳妥:location /admin/ { alias /var/www/my-app/dist/; }(结尾斜杠不能少) -
try_files的兜底项要写成/admin/index.html,不是/index.html - 否则 Nginx 会去找根目录下的
/index.html,可能返回其他项目的首页,甚至 404
API 接口必须单独拦截,避免被 try_files 吞掉
所有以 /api/ 开头的请求,不该进 try_files 流程,否则返回 index.html 导致接口失效:
- 在
location /前或同级,加一个明确的location /api/块 -
location /api/ { proxy_pass http://127.0.0.1:3000/; }(注意proxy_pass末尾的/) - Nginx 匹配是“最长前缀优先”,
/api/login一定先命中/api/,不会落到location /里
别漏掉 index 指令和 favicon 处理
看似次要,但缺一不可:
- 加上
index index.html;,确保访问根路径/时能正确加载入口 - 单独处理
favicon.ico:location = /favicon.ico { log_not_found off; expires 1d; add_header Cache-Control "public"; },避免它触发try_files多余查找 - 静态资源建议加缓存:
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ { expires 1y; }
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











