如何在Vite React SSG中配置未匹配路径重定向至404页面?
解决方案:Vite React SSG + React Router DOM 实现404页面重定向
这个功能完全可行,你的配置没生效大概率是路由顺序、预渲染配置或者重定向路径的问题,下面是具体的实现方案:
1. 调整路由配置
React Router的路由匹配是从上到下的,所以通配符路由(path: '*')必须放在所有路由的最后,确保它只会匹配前面未匹配到的路径。另外,重定向路径建议写完整路径(/404)而非相对路径,避免嵌套路由下的路径错误:
import { lazy } from 'react'; import Layout from './components/Layout'; export const routes = [ { path: '/', Component: Layout, children: [ // 所有业务路由放在最前面 { path: 'about', Component: lazy(() => import('@components/About')) }, { path: 'blog', Component: lazy(() => import('@components/Blog')) }, // 404页面路由 { path: '404', Component: lazy(() => import('@components/NotFound')) }, // 通配符路由,匹配所有未定义路径并重定向到404 { path: '*', redirect: '/404' }, ], }, ];
如果不想用重定向,也可以直接在通配符路由里渲染NotFound组件,这种方式更直接,避免重定向的路径问题:
export const routes = [ { path: '/', Component: Layout, children: [ // 业务路由... { path: 'about', Component: lazy(() => import('@components/About')) }, // 直接渲染404组件 { path: '*', Component: lazy(() => import('@components/NotFound')) }, ], }, ];
2. 配置Vite React SSG预渲染404页面
SSG模式下必须预生成404页面的静态文件,否则访问未定义路径时会找不到对应的HTML文件。在vite.config.js中,通过ssgOptions.routes指定需要预渲染的路径,包含/404:
import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; import { ssg } from 'vite-react-ssg'; export default defineConfig({ plugins: [ react(), ssg({ // 手动指定所有需要预渲染的路由,包括404 routes: async () => ['/', '/about', '/blog', '/404'], // 如果使用自动路由扫描,确保404组件所在路径被包含,或者手动添加 }), ], });
3. 部署时的服务器配置(可选但重要)
静态部署时,需要配置服务器将所有未匹配到的请求指向404.html,比如:
- Nginx:在配置文件中添加
try_files $uri $uri/ /404.html; - Netlify:在项目根目录创建
_redirects文件,添加/* /404.html 404 - Vercel:在
vercel.json中配置rewrites规则指向404页面
这样即使用户直接访问未定义的路径(比如/invalid-path),服务器也会返回预渲染好的404页面,再通过React Router的客户端路由匹配显示内容。
内容的提问来源于stack exchange,提问作者EBianchi
相关产品推荐
相关产品推荐

