Vue 3 开的 history 模式,首页进得去,点链接也正常,唯独在 /order/123 这种地址上按 F5,出来的是 nginx 的 404 页面,响应头里 server 写着 nginx/1.24.0。
直接访问时 nginx 会去 root 目录下找 order/123 这个文件和目录,两样都没有就 404,整个过程跟单页应用没关系。前端路由只负责浏览器里的跳转,刷新之后请求先落到 nginx。
打开站点配置,loCation / 里写的是 try_files $uri $uri/;,只有两段,最后没有兜底文件。这是我见过最多的一种「少写一段」:前两段找不到就直接 404,index.html 根本没机会返回。
补上 /index.html 后深层路由 200 了,但紧接着接口全挂。/api/user 也被这条规则兜成 index.html,前端拿到一坨 HTML 去 JSON.parse,报 Unexpected token <。解决办法是把 api 单独提出来用 location ^~ 放前面,优先级高于正则和普通前缀。
root 后面也别顺手加斜杠。我同事写成 /www/wwwroot/shop/dist/,try_files 拼出来的路径多一层,index.html 照样找不到,返回的还是那个 404,页面上看不出任何区别,只在 error.log 里多一行 open() failed。
验证是三条命令:curl -I 请求 /order/123 看 200 和 text/html;curl -I 请求 /api/user 看 401 和 application/json;再让前端连按三次 F5,Network 里没有一条 404。三个都过,配置才算写对。
root /www/wwwroot/shop/dist;
location ^~ /api/ {
proxy_pass http://127.0.0.1:8080;
}
location / {
try_files $uri $uri/ /index.html;
}
location ~* \.(js|css|png|jpg|svg|woff2)$ {
expires 30d;
try_files $uri =404;
} 