React Router(v6) HashRouter未知路由无法跳转至PageNotFound求助
解决React Router v6 HashRouter的未知路径重定向问题
问题原因
HashRouter仅负责处理URL中#之后的路径部分,#之前的路径由你的服务器接管。当用户访问类似yourdomain.com/random-path(不带#的非根路径)时,请求会先发送到服务器:
- 如果服务器配置为所有请求都返回SPA的
index.html(单页应用常见配置),React初始化时拿到的路径是/,自然会渲染<Home />组件,而非404页面。 - 如果服务器没有对应路径的资源,可能直接返回服务器端的404,但这不符合SPA的预期行为。
解决方案
方案1:服务器端配置(推荐)
修改服务器配置,仅允许根路径/返回index.html,其他路径直接返回404页面。不同服务器的配置示例:
- Nginx:
server { listen 80; server_name yourdomain.com; root /path/to/your/app; index index.html; # 根路径返回index.html location = / { try_files $uri $uri/ /index.html; } # 其他路径返回404 location / { return 404; } # 静态资源正常访问 location ~* \.(js|css|png|jpg|gif)$ { expires 1y; add_header Cache-Control "public, immutable"; } } - Apache:
<Directory /path/to/your/app> RewriteEngine On # 根路径允许访问 RewriteRule ^/$ /index.html [L] # 静态资源允许访问 RewriteRule ^(.*\.(js|css|png|jpg|gif))$ $1 [L] # 其他路径返回404 RewriteRule ^.*$ - [R=404,L] </Directory>
方案2:前端额外处理(无需改服务器)
如果无法修改服务器配置,可以在React根组件中检查window.location.pathname,当路径不是根路径时,主动跳转到哈希路由的404页面:
import { useEffect } from 'react'; import { Routes, Route, useNavigate } from 'react-router-dom'; import Home from './Home'; import AboutUs from './AboutUs'; import PageNotFound from './PageNotFound'; function App() { const navigate = useNavigate(); useEffect(() => { // 检测#前面的路径是否为根路径 if (window.location.pathname !== '/') { // 直接跳转到哈希路由的404页面 navigate('*'); } }, [navigate]); return ( <Routes> <Route path="/" element={<Home />} /> <Route path="about-us" element={<AboutUs />} /> {/* 其他路由 */} <Route path="*" element={<PageNotFound />} /> </Routes> ); } // 路由入口 function Root() { return ( <HashRouter> <App /> </HashRouter> ); } export default Root;
这样,当用户访问yourdomain.com/random-path时,前端会自动跳转到yourdomain.com/#/*,从而渲染<PageNotFound />组件。
内容的提问来源于stack exchange,提问作者Mohammed Shirhaan
相关产品推荐
相关产品推荐

