Next.js 13(App Dir)实现带www域名及本地化重定向方案
解决方案
我们可以在现有中间件中添加www域名重定向逻辑,同时保留原有的本地化跳转功能,确保两个需求同时实现。
调整后的中间件代码
import { i18n } from './i18n-config'; // 请确保你的i18n配置文件路径正确 export async function middleware(request) { const { nextUrl } = request; const { pathname, host } = nextUrl; // 1. 生产环境下处理www域名重定向 const isProduction = process.env.NODE_ENV === 'production'; const hasWwwPrefix = host.startsWith('www.'); if (isProduction && !hasWwwPrefix) { nextUrl.host = `www.${host}`; // 先检查路径是否已带本地化前缀,是则直接返回www重定向 const pathHasLocale = i18n.locales.some( locale => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}` ); if (pathHasLocale) { return Response.redirect(nextUrl, 301); } } // 2. 处理本地化跳转(保留原有逻辑) const pathHasLocale = i18n.locales.some( locale => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}` ); if (pathHasLocale) return; const defaultLocale = "ae"; nextUrl.pathname = `/${defaultLocale}${pathname}`; // 根据场景返回对应重定向状态码,生产环境用301利于SEO return Response.redirect(nextUrl, isProduction && !hasWwwPrefix ? 301 : 302); } // 配置中间件匹配范围,排除无需处理的路由 export const config = { matcher: [ '/((?!api|_next/static|_next/image|favicon.ico).*)', ], };
关键逻辑说明
- 环境判断:仅在生产环境触发www重定向,避免干扰开发调试流程。
- 重定向优先级:先处理域名前缀修正,再处理本地化路径补充,确保最终地址同时满足两个要求。
- 状态码选择:生产环境使用301永久重定向(利于搜索引擎优化),非生产环境用302临时重定向。
- 路由过滤:通过
matcher排除API、静态资源等无需处理的路径,提升中间件运行效率。
验证场景
| 用户输入 | 最终跳转地址 |
|---|---|
example.com | https://www.example.com/ae |
example.com/pk | https://www.example.com/pk |
www.example.com/about | https://www.example.com/ae/about |
内容的提问来源于stack exchange,提问作者Farooq Ali
相关产品推荐
相关产品推荐

