NextJS SSG页面如何实现slug路由的大小写不敏感匹配功能
针对 Next.js Pages Router 路由大小写不敏感匹配的最优解决方案
以下方案按优先度排序,可根据项目场景选择:
1. 全局301重定向(首选,无业务侵入+SEO友好)
直接在next.config.js中配置重定向规则,所有带大写字母的请求路径自动跳转到全小写路径,既解决匹配问题,还能避免重复内容导致的SEO权重分散,完全不需要修改现有业务代码:
// next.config.js module.exports = { async redirects() { return [ { source: '/:slug*', regex: '^(.*[A-Z].*)$', permanent: true, destination: (req) => { const lowerPath = req.params.slug.join('/').toLowerCase() return `/${lowerPath}${req.search || ''}` } } ] } }
如果你的Next.js版本不支持redirects的destination函数写法,可以改用Middleware方案。
2. Middleware 预处理请求(灵活适配各种场景)
Next.js 12及以上版本可使用Middleware在请求进入页面逻辑前统一处理,根目录新增middleware.js:
// middleware.js import { NextResponse } from 'next/server' export function middleware(request) { const { pathname, search } = request.nextUrl // 仅当路径包含大写字母时触发重定向 if (/[A-Z]/.test(pathname)) { const lowerCaseFullPath = pathname.toLowerCase() + search return NextResponse.redirect(new URL(lowerCaseFullPath, request.url)) } return NextResponse.next() } // 配置匹配规则,仅处理动态slug路径,避免静态资源、API接口被误拦截 export const config = { matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'], }
该方案不需要修改原有页面的getStaticPaths、getStaticProps逻辑,所有用户输入的大小写混合路径都会自动跳转到你预生成的小写静态路径。
3. 现有逻辑极简优化(最小改动适配)
如果你不想修改全局配置,可以直接优化现有冗余代码,完全不需要在组件内写useEffect跳转404:
优化getStaticProps
找不到数据时直接返回notFound: true,Next.js会自动渲染系统404页面:
export async function getStaticProps({ params }) { const { slug } = params const item = data.find(o => o.Practice_Code.trim().toLowerCase() === slug.toLowerCase()) if (!item) { return { notFound: true } } return { props: { item } } }
优化页面组件
去掉冗余的状态判断和跳转逻辑:
export default function Page({ item }) { const { isFallback } = useRouter() if (isFallback) return <div>Loading...</div> return <Item item={item} /> }
内容的提问来源于stack exchange,提问作者Dave
相关产品推荐
相关产品推荐

