You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3 Router历史模式下非主页URL报CANNOT GET错误求助

解决方案

核心问题

直接在浏览器输入子URL(比如/services)时,浏览器会先向服务器请求对应路径的物理文件,但服务器上根本不存在这个文件,所以返回404。这时候前端路由还没机会接管请求,必须让服务器把所有非静态资源的请求都转发到index.html,Vue Router才能处理路由逻辑。

1. 不同服务器的配置方案

Nginx

修改站点配置文件,在location /块中添加转发规则:

server {
    listen 80;
    server_name www.mywebpage.com;
    root /你的SPA打包后dist目录的绝对路径;

    location / {
        try_files $uri $uri/ /index.html; # 找不到资源就返回index.html
    }
}

修改后重启Nginx生效。

Apache

在项目根目录(或dist目录)创建.htaccess文件,写入:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

确保Apache开启了mod_rewrite模块。

Netlify

在项目根目录创建_redirects文件,添加一行:

/*    /index.html   200

部署时Netlify会自动应用该规则。

Vercel

在项目根目录创建vercel.json文件,内容如下:

{
  "rewrites": [
    { "source": "/(.*)", "destination": "/index.html" }
  ]
}

Express(Node.js服务器)

添加中间件处理所有请求:

const express = require('express');
const path = require('path');
const app = express();

app.use(express.static(path.join(__dirname, 'dist')));

// 所有非静态资源请求转发到index.html
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});

app.listen(3000);

2. 前端路由补充检查

你的前端路由配置没问题,但要注意通配路由必须放在所有路由的最后,否则会覆盖前面的路由规则,比如:

const routes = [
  { path: '/', redirect: '/page-home' },
  { path: '/index.html', redirect: '/page-home' },
  { path: '/page-home', name: 'Home', component: landing },
  { path: '/services', name: 'Services', component: Services },
  // 通配路由放在最后
  { path: '/:pathMatch(.*)*', name: 'NotFound', component: landing }
];

完成服务器配置后,直接输入子URL就能正常访问了。

内容的提问来源于stack exchange,提问作者Yolo_chicken

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 13:12:17