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

Vite开发环境嵌套路由刷新报404,如何配置SPA客户端路由?

解决Vite开发环境中React Router嵌套路由刷新404问题

要解决这个问题,只需在Vite配置中开启historyApiFallback,让开发服务器将所有无法匹配静态资源的请求重定向到根目录的index.html,具体操作如下:

  1. 打开项目根目录下的vite.config.js(TypeScript项目对应vite.config.ts)
  2. 在配置对象中添加server字段,启用historyApiFallback:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  server: {
    historyApiFallback: true
  }
})

配置生效后,刷新嵌套路由页面时,Vite开发服务器会自动返回根目录的index.html,由React Router接管路由解析,不会再出现404错误。

如果需要针对特定路径做精细控制,可以给historyApiFallback传入配置对象,示例如下:

server: {
  historyApiFallback: {
    rewrites: [
      // 仅让/nested开头的路径重定向到index.html
      { from: /^\/nested\/.*$/, to: '/index.html' }
    ]
  }
}

多数SPA路由场景下,直接将historyApiFallback设为true就能满足需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 14:12:04