You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js 13(TypeScript)生产环境子域名映射本地化目录失效问题

调试建议与解决方案

一、核心调试步骤

1. 修正Host头获取逻辑

生产环境中,反向代理(如Vercel、Nginx)可能会修改Host头,导致无法正确识别子域名。优先读取代理传递的真实域名头:

function getLocale(request: NextRequest): Locale {
  // 优先取代理传递的真实Host,适配不同部署平台
  const host = request.headers.get("x-forwarded-host") || request.headers.get("host");
  const subdomain = getValidSubdomain(host as string);

  if (subdomain) {
    return subdomainLocale[subdomain];
  } else {
    return i18n.defaultLocale;
  }
}

2. 添加生产环境日志排查

在middleware中插入关键变量日志,部署后查看生产环境日志(如Vercel函数日志、服务器日志)定位问题:

export function middleware(request: NextRequest) {
  const url = request.nextUrl.clone();
  if (PUBLIC_FILE.test(url.pathname) || url.pathname.includes("_next")) return;
  
  // 输出调试日志
  const host = request.headers.get("x-forwarded-host") || request.headers.get("host");
  console.log("[Middleware] Host:", host);
  console.log("[Middleware] Request Path:", url.pathname);
  
  const locale = getLocale(request);
  console.log("[Middleware] Matched Locale:", locale);
  
  url.pathname = `/${locale}${url.pathname}`;
  console.log("[Middleware] Rewritten Path:", url.pathname);
  
  return NextResponse.rewrite(url);
}

3. 修正公共文件匹配正则

原正则/\.(.*)$/会误匹配包含点的路径(如/en-US),改用精准匹配静态文件扩展名的正则:

const PUBLIC_FILE = /\.(ico|png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)$/;

二、官方原生替代方案

Next.js 13 App Router支持基于域名的本地化,无需手动编写middleware,配置更稳定可靠:

1. 配置next.config.js

/** @type {import('next').NextConfig} */
const nextConfig = {
  i18n: {
    locales: ["en-US", "he-IL", "fr-FR"],
    defaultLocale: "en-US",
    localeDetection: false,
    domains: [
      {
        domain: "www.domain.com",
        defaultLocale: "en-US",
      },
      {
        domain: "he.domain.com",
        defaultLocale: "he-IL",
      },
      {
        domain: "fr.domain.com",
        defaultLocale: "fr-FR",
      },
    ],
  },
};

module.exports = nextConfig;

2. 保留原有目录结构

继续使用src/app/[locale]的目录结构,示例:

src/app/
├── [locale]/
│   ├── page.tsx
│   └── about/
│       └── page.tsx
└── layout.tsx

3. 移除自定义middleware

官方会自动处理子域名到对应locale目录的映射,无需手动rewrite请求。

三、额外注意事项

  • 确认生产环境DNS配置:所有子域名均指向你的Next.js部署服务器/平台。
  • 若使用Vercel部署,需在项目设置中添加所有子域名到Domains列表并完成验证。
  • 检查生产环境缓存规则,清除旧缓存后再测试。

内容的提问来源于stack exchange,提问作者Pavel Rapoport

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 13:54:54