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

React页面刷新后丢失路由历史并出现404错误求助

解决React生产环境刷新非首页404及路由历史丢失问题

1. 修正.htaccess重写规则

你的现有规则框架正确,但可以补充QSA参数确保查询字符串传递,同时优化规则逻辑:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  # 直接访问index.html时跳过重写
  RewriteRule ^index\.html$ - [L]
  # 排除真实存在的文件、目录、软链接
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-l
  # 重写所有请求到index.html,保留查询参数
  RewriteRule ^(.*)$ /index.html [QSA,L]
</IfModule>

# php -- BEGIN cPanel-generated handler, do not edit
# Set the “ea-php74” package as the default “PHP” programming language.
<IfModule mime_module>
  AddHandler application/x-httpd-ea-php74 .php .php7 .phtml
</IfModule>
# php -- END cPanel-generated handler, do not edit

如果应用部署在子目录(如https://xxx.com/my-app/),需同步修改RewriteBase和重写目标:

RewriteBase /my-app/
RewriteRule ^(.*)$ /my-app/index.html [QSA,L]

2. 调整package.json的homepage配置

  • 根目录部署:设为"/"
  • 子目录部署:设为"/你的子目录名/"
    不要使用".",这会导致资源路径解析异常,干扰路由逻辑。

3. 确认路由基础配置

确保路由被BrowserRouter包裹(而非HashRouter),这是单页应用路由的标准配置:

import { BrowserRouter, Routes, Route } from 'react-router-dom';

function App() {
  return (
    <BrowserRouter>
      {/* 导航栏组件放在这里 */}
      <Routes>
        <Route path='/' element={<NewHome />} />
        <Route path='/about' element={<AboutPage />} />
      </Routes>
    </BrowserRouter>
  );
}

4. 服务器环境验证

  • 确认cPanel中网站的文档根目录指向React应用的build文件夹
  • 检查Apache是否启用了mod_rewrite模块(可在cPanel的Apache模块管理中查看)
  • 排查上级目录的.htaccess是否存在冲突规则

路由历史保留说明

刷新页面时路由历史丢失,本质是服务器返回404导致React无法加载并解析路由状态。当上述配置生效后,所有非真实文件/目录的请求都会被转发到index.html,React Router就能正确解析URL、恢复对应路由状态,路由历史也会自然保留。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 06:42:38