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

在Vercel部署React+TypeScript+Vite项目时刷新页面出现404错误

解决Vite+React+TS项目部署后刷新404问题

问题原因

单页应用(SPA)的路由由前端JS控制,首次访问时浏览器加载index.html,后续路由切换都是前端完成。但刷新页面时,浏览器会直接向服务器请求当前路径的资源,而服务器上不存在对应路径的静态文件,因此返回404。

解决方案

1. Nginx部署场景

修改Nginx配置文件,添加try_files指令,将所有请求转发到index.html:

server {
  listen 80;
  server_name 你的域名;
  root 你的项目dist目录绝对路径;
  index index.html;

  location / {
    try_files $uri $uri/ /index.html;
  }
}

修改后重启Nginx生效。

2. Vercel部署场景

在项目根目录创建vercel.json文件,添加路由重写规则:

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

3. Netlify部署场景

在项目根目录创建_redirects文件(文件名以下划线开头),添加一行规则:

/* /index.html 200

4. 子路径部署注意事项

如果项目部署在域名的子路径下(比如https://xxx.com/my-app/),需要在vite.config.ts中配置base属性:

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

export default defineConfig({
  plugins: [react()],
  base: '/my-app/' // 替换为你的实际子路径
})

内容的提问来源于stack exchange,提问作者MD Jahid Hasan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 19:57:02