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

Vue+TypeScript服务器请求全重定向404,本地运行正常

Vue+TS项目部署后全路由404问题解决指南

1. 确认路由模式与服务器配置

从你提供的Router代码来看,应该使用了history模式(Vue2里的mode: 'history',Vue3里的createWebHistory())。这种模式下,用户直接访问子路由(比如/home)时,服务器会尝试查找对应物理文件,但SPA只有一个index.html,因此会返回404,必须给服务器添加fallback规则:

  • Nginx配置:在站点配置中添加
    location / {
      try_files $uri $uri/ /index.html;
    }
    
  • Apache配置:启用mod_rewrite后,在.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>
    
  • Netlify/Vercel平台配置:
    • Netlify:在项目根目录创建_redirects文件,内容为/* /index.html 200
    • Vercel:在项目根目录创建vercel.json,内容如下:
      {
        "rewrites": [{"source": "/(.*)", "destination": "/index.html"}]
      }
      

2. 检查base路径配置

如果项目部署在子路径下(比如https://xxx.com/my-project/),需要同步配置两处:

  • Router配置:
    Vue2:
    const router = new VueRouter({
      mode: 'history',
      base: '/my-project/', // 对应你的部署子路径
      routes: [...]
    })
    
    Vue3:
    const router = createRouter({
      history: createWebHistory('/my-project/'),
      routes: [...]
    })
    
  • 构建配置:
    Vue2(vue.config.js):
    module.exports = {
      publicPath: '/my-project/'
    }
    
    Vue3(vite.config.ts):
    export default defineConfig({
      base: '/my-project/'
    })
    

3. 检查404路由的位置

你配置的通配符404路由必须放在所有路由的最后面,否则会优先匹配所有路径,导致正常路由无法访问:

const routes = [
  // 所有正常路由定义在前面
  { path: '/home', component: Home },
  // ...其他路由
  // 404路由放在最后
  { path: '/:catchAll(.*)', component: NotFound }
]

4. 验证静态文件部署路径

确保将打包后的dist(或build)文件夹完整上传到服务器的静态资源目录,服务器能正常访问index.html及其引用的js、css文件。如果静态资源路径错误,页面加载异常也会间接引发路由跳转问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 12:05:22