Next.js App Router国际化:默认语言根路径重定向SEO问题
解决Next.js /app路由下默认语言URL带前缀的SEO问题
针对你迁移到/app路由后,默认语言en被强制加上/en前缀、原有根路径被重定向的问题,不需要依赖官方的i18n路由配置,手动调整目录结构+中间件就能实现需求:
1. 调整目录结构
直接把默认语言(en)的页面放在/app根目录,西班牙语(es)的页面放在/app/es子目录:
/app/page.tsx→ 对应example.com/(英文首页)/app/blog/[slug]/page.tsx→ 对应example.com/blog/my-post(英文博客)/app/es/page.tsx→ 对应example.com/es(西班牙文首页)/app/es/blog/[slug]/page.tsx→ 对应example.com/es/blog/mi-articulo(西班牙文博客)
2. 用中间件处理重定向与语言检测
创建middleware.ts文件,拦截/en路径重定向到根目录,同时处理用户语言偏好:
import { NextResponse } from 'next/server'; import type { NextRequest } from 'next/server'; export function middleware(request: NextRequest) { const pathname = request.nextUrl.pathname; // 把/en开头的路径重定向到去掉前缀的版本,避免重复内容影响SEO if (pathname.startsWith('/en')) { const newPathname = pathname.replace(/^\/en/, '') || '/'; return NextResponse.redirect(new URL(newPathname, request.url)); } // 可选:根据cookie或浏览器语言偏好自动切换语言 const langCookie = request.cookies.get('NEXT_LOCALE')?.value; const acceptLanguage = request.headers.get('accept-language')?.split(',')[0].split('-')[0]; const preferredLang = langCookie || acceptLanguage || 'en'; // 如果用户偏好西班牙语但访问的是非/es路径,重定向到/es版本 if (preferredLang === 'es' && !pathname.startsWith('/es')) { return NextResponse.redirect(new URL(`/es${pathname}`, request.url)); } return NextResponse.next(); } // 指定要匹配的路由规则 export const config = { matcher: ['/', '/en/:path*', '/es/:path*', '/blog/:path*'], };
3. 实现语言切换组件
在客户端组件中创建语言切换按钮,切换时设置cookie并跳转正确路径:
'use client'; import { useRouter } from 'next/navigation'; import { cookies } from 'next/headers'; export default function LanguageSwitcher() { const router = useRouter(); const switchToEnglish = () => { cookies().set('NEXT_LOCALE', 'en'); const targetPath = window.location.pathname.replace(/^\/es/, '') || '/'; router.push(targetPath); }; const switchToSpanish = () => { cookies().set('NEXT_LOCALE', 'es'); const currentPath = window.location.pathname === '/' ? '' : window.location.pathname; router.push(`/es${currentPath}`); }; return ( <div className="lang-switcher"> <button onClick={switchToEnglish}>English</button> <button onClick={switchToSpanish}>Español</button> </div> ); }
4. SEO与静态生成注意事项
- Hreflang标签:在每个页面的meta标签中添加hreflang,比如英文首页添加:
西班牙文首页对应反向配置,确保搜索引擎识别不同语言版本。<link rel="alternate" href="https://example.com/" hreflang="en" /> <link rel="alternate" href="https://example.com/es" hreflang="es" /> - Sitemap与Robots:生成sitemap时只包含根路径和/es路径,排除/en路径;在robots.txt中禁止爬虫抓取/en开头的内容。
- 静态生成:如果用SSG,在
generateStaticParams中为西班牙语页面生成对应的slug参数,确保静态资源正确构建。
内容的提问来源于stack exchange,提问作者Fabricio Espinoza
相关产品推荐
相关产品推荐

