NextJS中redirects()函数失效,请求排查代码修复
问题修复方案
1. 修正redirects配置中的permanent类型错误
你在重定向规则里把permanent设为了字符串'true',但Next.js要求这个值必须是布尔类型,字符串值会导致重定向规则不生效。修改如下:
async redirects(){ return[ { source: '/plain-language/accessible-webdesign', destination: '/plain-language/for-disabled-persons', permanent: true // 去掉引号,改为布尔值 } ] },
2. 修正Next.js配置的导出方式
你的配置导出代码写法错误,withPWA({nextConfig})会把nextConfig作为嵌套属性传递,而非合并到Next.js核心配置中,这直接导致你的redirects规则没被系统识别。正确的导出方式应该是直接传递nextConfig对象:
// 替换原来的导出语句 module.exports = withBundleAnalyzer(withPWA(nextConfig));
额外优化建议:优化语言切换逻辑
目前你的切换按钮仅简单添加/移除/plain-language/前缀,容易出现路径不匹配问题。建议维护一个路径映射表,在切换时直接匹配对应目标路径,避免依赖重定向:
// 在切换按钮所在组件中定义映射表 const pathMappings = { '/accessible-webdesign': '/plain-language/for-disabled-persons', '/about': '/plain-language/about', // 补充其他需要映射的路径 }; // 切换语言的核心逻辑 const togglePlainLanguage = () => { const currentPath = window.location.pathname; let targetPath; if (currentPath.startsWith('/plain-language/')) { // 从简明版切回标准版,移除前缀 targetPath = currentPath.replace('/plain-language/', '/'); } else { // 从标准版切到简明版,优先用映射路径, fallback 到默认前缀规则 targetPath = pathMappings[currentPath] || `/plain-language${currentPath}`; } window.location.href = targetPath; };
这种方式能直接跳转到正确页面,无需依赖重定向,同时避免404错误。
内容的提问来源于stack exchange,提问作者Cioccoluna
相关产品推荐
相关产品推荐

