GitLab Pages部署React Router v6单页应用路由问题求助
解决GitLab Pages部署React客户端路由子路由404问题
问题原因
GitLab Pages是静态文件托管服务,直接访问子路由时,服务器会尝试查找对应物理文件,但客户端路由的子路由没有实际文件,因此返回404;而通过根路由链接跳转是客户端路由内部处理,不会触发服务器文件查找,所以正常。
解决方案
1. 配置404.html重定向脚本
在项目根目录创建或修改404.html,添加以下内容:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Loading...</title> <script> // 捕获当前请求的完整路径(含查询参数) const fullPath = window.location.pathname + window.location.search; // 重定向到项目根页面,携带原路径作为参数 window.location.replace('/iiser-bhopal/?redirect=' + encodeURIComponent(fullPath)); </script> </head> <body></body> </html>
2. 在React应用中处理重定向参数
在src/App.tsx中添加逻辑,读取URL中的redirect参数并跳转到对应路由:
import { useEffect } from 'react'; import { useNavigate, Routes, Route } from 'react-router-dom'; // 导入你的页面组件,示例: import Home from './pages/Home'; import Description from './pages/Description'; function App() { const navigate = useNavigate(); useEffect(() => { const params = new URLSearchParams(window.location.search); const redirectPath = params.get('redirect'); if (redirectPath) { // 跳转到目标子路由 navigate(decodeURIComponent(redirectPath)); // 清除URL中的redirect参数,避免重复处理 params.delete('redirect'); window.history.replaceState({}, document.title, `${window.location.pathname}${params.toString() ? `?${params.toString()}` : ''}`); } }, [navigate]); return ( <Routes> <Route path="/" element={<Home />} /> <Route path="/description" element={<Description />} /> {/* 其他子路由配置 */} </Routes> ); } export default App;
3. 确认CI配置正确
你的.gitlab-ci.yml中已经包含cp 404.html public/,确保这个步骤正常执行,将404.html复制到部署目录。
完成以上配置后,直接访问子路由URL时,会先触发404.html的重定向,将路径传递给index.html,再由React Router解析并渲染对应页面,解决404问题。
内容的提问来源于stack exchange,提问作者Sattwik Kumar Sahu
相关产品推荐
相关产品推荐

