核心是配置try_files $uri $uri/ /index.html;实现spa路由兜底,需结合前端history模式、子路径部署前缀、静态资源分离及api代理规则协同生效。

核心是让 Nginx 在找不到真实文件时,把请求兜底给 index.html,由前端路由接管解析。只加一行 try_files 不够,得结合项目部署路径、静态资源规则和 API 代理逻辑一起配。
确认是否启用了 history 模式
Vue Router 或 React Router 必须显式启用 history 模式,且不能依赖 hash(如 /#/user)。检查前端路由配置:
- Vue Router 3:确保
mode: 'history' - Vue Router 4:使用
createWebHistory(),而非createWebHashHistory() - React Router:用
createBrowserRouter或<routerprovider></routerprovider>,避免HashRouter
若仍用 hash 模式,Nginx 根本无需特殊配置——因为浏览器根本不会把 # 后内容发给服务器。
基础 Nginx 配置(根路径部署)
适用于部署在域名根目录(如 https://example.com/)的项目:
location / {
root /path/to/dist;
index index.html;
try_files $uri $uri/ /index.html;
}
这行 try_files $uri $uri/ /index.html 的含义是:
- 先查请求路径是否对应真实文件(如
/js/app.js)→ 是则直接返回 - 再查是否为目录(如
/assets/)→ 是则尝试找该目录下的index.html - 都失败 → 统一返回
/index.html,交由前端 JS 解析当前 URL
子路径部署(如 /admin/ 或 /app/)
当应用不是放在根目录,而是二级路径(例如 https://example.com/admin/),必须同步调整三处:
-
前端构建配置:Vue CLI 设置
publicPath: '/admin/';Vite 设置base: '/admin/' -
Nginx location 路径匹配:写成
location /admin/ { ... } -
try_files 回退路径:必须写为
try_files $uri $uri/ /admin/index.html;(不能漏掉前缀)
否则会出现:请求 /admin/user → Nginx 找 /admin/user 文件失败 → 回退到 /index.html(404),而不是 /admin/index.html。
避免 403 和重定向循环
403 常因以下配置冲突引发:
- 在
location /块里同时写了try_files和proxy_pass,导致非静态路径被错误代理 - API 接口路径(如
/api/)与前端路由重叠,未提前拦截 - 静态资源(
.js、.css、图片)因权限或路径问题返回 403
正确做法是分离处理:
location / {
try_files $uri $uri/ /index.html;
}
<p>location /api/ {
proxy_pass <a href="https://www.php.cn/link/65b5b8d1f89bf53a5713bc3afdd83e9e">https://www.php.cn/link/65b5b8d1f89bf53a5713bc3afdd83e9e</a>;
proxy_set_header Host $host;
}</p><h1>显式声明静态资源,防止误入 try_files 回退</h1><p>location ~* .(js|css|png|jpg|gif|ico|woff2?)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}</p>
这样,所有带后缀的资源走静态服务,API 请求走代理,其余全部兜底到 index.html,不交叉、不冲突。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











