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

Nginx环境下Vue SPA未跳转到自定义404页面问题

解决方案

1. 修复Vue Router的404路由配置

问题核心在于Vue Router的NotFound路由配置有误,导致部署后无法正确匹配未定义路由。修改如下:

{
    path: '/',
    name: 'MainLayout',
    component: () => import('../layouts/MainLayout.vue'),
    meta: {
        middleware: 'translation'
    },
    children: [
        {
            path: '',
            name: 'Index',
            component: () => import('@/application/views/Index.vue')
        },
       // 其他路由
        {
            // 去掉path开头的斜杠,子路由需用相对路径
            path: ':catchAll(.*)',
            // 修复懒加载写法,添加箭头函数
            component: () => import('@/application/views/404Page.vue'),
            name: 'NotFound'
        }
    ]
},

关键修改说明:

  • 子路由路径无需开头斜杠:父路由已为/,使用相对路径':catchAll(.*)'才能正确匹配所有未定义的子路径。
  • 组件导入改为箭头函数:() => import(...)是Vue Router懒加载的标准写法,原代码直接写import(...)会提前加载组件,虽不影响匹配,但不符合懒加载规范。

2. 简化Nginx配置

你初始的Nginx配置已满足SPA路由需求,无需额外添加error_page和location = /index.html规则,保留以下配置即可:

server {
    listen 80;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate /etc/nginx/certs/fullchain.pem;
    ssl_certificate_key /etc/nginx/certs/privkey.pem;

    location / {
        root /usr/share/nginx/html;
        index index.html;
        # 将无法匹配静态资源的请求转发到index.html,由Vue Router处理路由
        try_files $uri $uri/ /index.html;
    }
}

3. 验证步骤

  • 重新打包项目:执行npm run build生成最新dist文件。
  • 更新服务器静态文件:将dist目录下所有文件覆盖到/usr/share/nginx/html。
  • 重启Nginx:执行sudo systemctl restart nginx使配置生效。
  • 测试未定义路由:此时应能正常显示404Page.vue内容,同时保留MainLayout的Header和Footer。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 08:57:08