Next.js如何处理同层级静态页与SSR页的动态路由配置需求
解决方案
方案一:next.config.js 静态重写(优先推荐)
该方案在构建阶段就确定路由匹配规则,运行时无额外性能损耗,适合分类路径更新频率较低的场景。
- 第一步:拆分两类页面到独立文件
在pages目录下创建两个独立页面,避免在同一文件内混合三类生成函数:pages/[[...slug]].js:负责静态页面渲染,保留原有getStaticPaths、getStaticProps逻辑pages/_internal-category/[[...category]].js:负责SSR分类页渲染,保留原有getServerSideProps逻辑
带_前缀的路径默认不会被用户直接访问,仅作为内部路由使用。
- 第二步:修改
next.config.js配置重写规则
构建时预先拉取WordPress全量分类路径,将分类路径内部重写到SSR路由,用户侧URL完全不变:// next.config.js module.exports = async () => { // 构建时从WordPress拉取所有分类的完整路径 const allCategoryPaths = await fetch('你的WordPress分类查询接口') .then(res => res.json()) .then(categories => categories.map(item => item.fullPath)) return { async rewrites() { return [ // 分类路径重写至内部SSR路由 ...allCategoryPaths.map(path => ({ source: path, destination: `/internal-category${path}` })), // 剩余路径走静态页面路由 { source: '/:path*', destination: '/:path*' } ] } } }
方案二:Middleware 运行时路由匹配
适合分类路径更新频繁,无法每次更新都重新构建的场景,在请求进入时动态判断路由类型。
- 第一步:同上拆分两类页面到独立文件
- 第二步:根目录新建
middleware.js实现运行时重写// middleware.js import { NextResponse } from 'next/server' // 缓存分类路径判断结果,避免重复请求WordPress const categoryPathCache = new Map() export async function middleware(request) { const currentPath = request.nextUrl.pathname // 跳过静态资源、内置路径的判断 if (currentPath.startsWith('/_next') || currentPath.startsWith('/api') || currentPath.match(/\.(png|jpg|ico|svg)$/)) { return NextResponse.next() } let isCategory = categoryPathCache.get(currentPath) if (isCategory === undefined) { // 调用WordPress接口判断当前路径是否为分类页 isCategory = await fetch(`你的WordPress路径类型判断接口?path=${encodeURIComponent(currentPath)}`) .then(res => res.ok) // 缓存1小时,可根据业务调整 categoryPathCache.set(currentPath, isCategory) setTimeout(() => categoryPathCache.delete(currentPath), 3600 * 1000) } if (isCategory) { // 内部重写至SSR路由,用户侧URL不变 return NextResponse.rewrite(new URL(`/internal-category${currentPath}`, request.url)) } return NextResponse.next() } export const config = { matcher: '/:path*' }
内容的提问来源于stack exchange,提问作者Alejandro
相关产品推荐
相关产品推荐

