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

Vite+React Router部署至Render/Vercel后刷新非首页出现404错误

React Router 刷新非首页404问题解决(Render/Vercel部署)

问题根源

这是单页应用(SPA)的典型问题:React Router的路由是前端在浏览器层面处理的,刷新非首页路径时,服务器会尝试查找对应物理路径的文件(比如/about对应的about.html),但这些文件实际不存在,所以返回404。首页刷新正常是因为服务器默认会返回根目录的index.html。

具体解决方案

1. Vite 项目基础配置

在项目根目录的vite.config.js中添加/调整以下配置,确保打包和本地开发的路由行为一致:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  // 若部署在子路径,这里填对应子路径,否则留'/'即可
  base: '/',
  build: {
    outDir: 'dist',
  },
  server: {
    // 本地开发时模拟生产环境的路由重写
    historyApiFallback: true,
  },
})

2. Render 平台配置

静态站点部署方式

在项目的public目录下新建_redirects文件,写入以下内容:

/*    /index.html   200

这个文件会告诉Render服务器,所有请求都重定向到index.html,交给React Router处理路由。

Node.js Web服务部署方式

如果是用Node.js(比如Express)做服务端,需要在服务代码里添加路由重写逻辑:

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

// 托管打包后的静态资源
app.use(express.static(path.join(__dirname, 'dist')));

// 所有非API请求都返回index.html
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});

app.listen(process.env.PORT || 3000);

3. Vercel 平台配置

在项目根目录新建vercel.json文件,写入以下配置:

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

该配置会让Vercel将所有请求重定向到index.html,由前端路由接管处理。

验证操作

  1. 执行npm run build重新打包项目
  2. 将更新后的代码重新部署到对应平台
  3. 刷新非首页路径(比如/about),确认不再出现404错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 15:35:00