部署在GitHub Pages的React.tsx项目直接访问非首页路由返回404如何解决
问题原因
GitHub Pages 作为静态资源托管服务,仅会响应真实存在的静态文件路径。React 项目如果使用 BrowserRouter(基于 HTML5 History API 实现的前端路由),所有路由跳转逻辑都在前端侧执行,服务端没有对应非首页路径的真实文件资源,因此直接访问或刷新非首页路径时会触发 GitHub Pages 默认的 404 逻辑。
解决方案
方案1:添加自定义404.html重定向(推荐,无特殊路径前缀)
该方案无需修改原有路由模式,不会改变路径格式,兼容性最好。
- 在项目
public目录下新建404.html文件,写入以下代码:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script type="text/javascript"> const fullPath = window.location.pathname + window.location.search + window.location.hash; const repoName = window.location.pathname.split('/')[1] || ''; window.location.replace(`/${repoName}#/redirect?path=` + encodeURIComponent(fullPath)); </script> </head> <body></body> </html>
- 在应用入口路由逻辑中添加重定向处理,以React Router v6为例,在
App.tsx中添加如下代码:
import { useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; function App() { const navigate = useNavigate(); useEffect(() => { if (window.location.hash.startsWith('#/redirect?path=')) { const targetPath = decodeURIComponent(window.location.hash.split('path=')[1]); window.history.replaceState(null, '', targetPath); navigate(targetPath, { replace: true }); } }, [navigate]); // 此处保留原有应用逻辑和路由定义 return <>{/* 原有组件内容 */}</> }
- 重新打包部署到GitHub Pages即可生效。
方案2:切换路由模式为HashRouter(操作简单)
如果可以接受路径带#前缀,直接替换路由模式即可,无需额外配置:
// 替换前 import { BrowserRouter } from 'react-router-dom'; ReactDOM.createRoot(document.getElementById('root')!).render( <BrowserRouter> <App /> </BrowserRouter> ); // 替换后 import { HashRouter } from 'react-router-dom'; ReactDOM.createRoot(document.getElementById('root')!).render( <HashRouter> <App /> </HashRouter> );
注意事项
- 如果项目部署在GitHub Pages子路径(访问地址格式为
https://<用户名>.github.io/<仓库名>/),需要给路由组件添加basename属性,取值为你的仓库名,示例:
<BrowserRouter basename="/你的仓库名"> <!-- 或 --> <HashRouter basename="/你的仓库名">
内容的提问来源于stack exchange,提问作者Arasto
相关产品推荐
相关产品推荐

