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

Next.js构建后站点地图链接带/en/前缀该如何移除

Next.js next-sitemap 移除/en/语言前缀配置修复方案

问题原因

  • 核心逻辑错误:你配置中定义的defaultRegion值为us,实际需要移除的是/en/前缀,原判断逻辑完全无法命中
  • 语法报错原因:如果第一行就触发报错,大概率是你使用了v4及以上版本的next-sitemap,该版本已默认采用ES模块规范,不再支持CommonJS的module.exports写法
  • 遗漏站点域名拼接:你当前返回的loc仅为处理后的路径,未拼接站点域名,会导致最终生成的sitemap链接不完整

修复代码

如果你使用的是v3及以下版本的next-sitemap(支持CommonJS)

next-sitemap.js 完整代码:

// 把us改为要移除的语言标识en
const defaultRegion = 'en';
module.exports = {
  siteUrl: process.env.NEXT_PUBLIC_SITE_URL,
  generateRobotsTxt: false,
  sitemapSize: 7000,
  transform: async (config, path) => {
    const defaultLocalePath = `/${defaultRegion}/`;
    let transformedPath = path;
    // 匹配前缀并移除
    if (path.startsWith(defaultLocalePath)) {
      transformedPath = path.replace(defaultLocalePath, '/');
    }
    // 拼接完整站点链接
    const fullUrl = new URL(transformedPath, config.siteUrl).href;
    return {
      loc: fullUrl,
      changefreq: config.changefreq,
      priority: config.priority,
      lastmod: config.autoLastmod ? new Date().toISOString() : undefined,
      alternateRefs: config.alternateRefs ?? [],
    };
  },
};

如果你使用的是v4及以上版本的next-sitemap(ES模块规范)

首先把配置文件名改为next-sitemap.config.js,完整代码:

const defaultRegion = 'en';
export default {
  siteUrl: process.env.NEXT_PUBLIC_SITE_URL,
  generateRobotsTxt: false,
  sitemapSize: 7000,
  transform: async (config, path) => {
    const defaultLocalePath = `/${defaultRegion}/`;
    let transformedPath = path;
    if (path.startsWith(defaultLocalePath)) {
      transformedPath = path.replace(defaultLocalePath, '/');
    }
    const fullUrl = new URL(transformedPath, config.siteUrl).href;
    return {
      loc: fullUrl,
      changefreq: config.changefreq,
      priority: config.priority,
      lastmod: config.autoLastmod ? new Date().toISOString() : undefined,
      alternateRefs: config.alternateRefs ?? [],
    };
  },
};

生效验证

配置修改完成后重新执行next build,再查看生成的sitemap文件,即可看到/en/前缀已经被移除,链接格式符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 10:54:00