Nuxt4配置指南:sitemap.xml与robots.txt

Nuxt4配置指南:sitemap.xml与robots.txt

一、安装必要模块

1.1 安装sitemap模块

npx nuxi@latest module add sitemap

1.2 安装robots模块(可选)

如果需要动态生成robots.txt,可安装官方模块:

npx nuxi@latest module add robots

二、配置sitemap.xml

2.1 基础配置(nuxt.config.ts)

export default defineNuxtConfig({
  // 站点基础配置
  site: {
    url: 'https://your-domain.com'// 替换为你的域名
    name: '你的网站名称',
    description: '你的网站描述'
  },
  
  // 模块配置
  modules: [
    '@nuxtjs/sitemap',
    '@nuxtjs/robots' // 如果安装了robots模块
  ],
  
  // Sitemap配置
  sitemap: {
    autoLastmod: true// 自动添加最后修改时间
    cacheMaxAgeSeconds: 60 * 60 * 24// 缓存时间(1天)
    exclude: [
      '/admin/**'// 排除管理后台路径
      '/login',
      '/register'
    ],
    xsl: true// 启用默认样式表
    sources: ['/api/sitemap'// 动态路由数据源
  }
})

2.2 动态路由处理

2.2.1 创建API端点(server/api/sitemap.ts)

export default defineSitemapEventHandler(async () => {
  // 1. 静态路由
  const staticRoutes = [
    {
      loc: '/',
      changefreq: 'daily',
      priority: 1.0,
      lastmod: new Date()
    },
    {
      loc: '/about',
      changefreq: 'monthly',
      priority: 0.8,
      lastmod: new Date('2025-01-15')
    },
    {
      loc: '/contact',
      changefreq: 'monthly',
      priority: 0.7,
      lastmod: new Date('2025-02-10')
    }
  ];
  
  // 2. 从API获取动态路由(示例)
  try {
    const posts = await $fetch('https://api.example.com/posts', {
      method: 'GET',
      params: { limit: 100 }
    });
    
    const dynamicRoutes = posts.map(post => ({
      loc: `/posts/${post.slug}`,
      changefreq: 'weekly',
      priority: 0.9,
      lastmod: new Date(post.updatedAt),
      // 可选:添加图片信息
      images: post.images?.map(img => ({
        loc: img.url,
        caption: img.alt
      }))
    }));
    
    return [...staticRoutes, ...dynamicRoutes];
  } catch (error) {
    console.error('获取动态路由失败:', error);
    return staticRoutes; // 失败时至少返回静态路由
  }
});

2.2.2 多站点地图配置(适用于大量URL)

如果网站URL超过5000个,建议拆分多个站点地图:

sitemap: {
  sitemaps: {
    posts: {
      sources: ['/api/sitemap/posts'],
      default: { changefreq: 'weekly', priority: 0.8 }
    },
    pages: {
      sources: ['/api/sitemap/pages'],
      default: { changefreq: 'monthly', priority: 0.6 }
    },
    products: {
      sources: ['/api/sitemap/products'],
      default: { changefreq: 'daily', priority: 0.9 }
    }
  }
}

三、配置robots.txt

3.1 静态文件方式(推荐)

在public目录下创建robots.txt:

# 允许所有搜索引擎抓取
User-agent: *
Allow: /

# 排除管理后台和账户相关页面
Disallow: /admin/
Disallow: /account/*
Disallow: /api/*

# 排除搜索结果页面
Disallow: /search?*

# 站点地图地址
Sitemap: https://your-domain.com/sitemap.xml

# 针对特定爬虫的设置
User-agent: Baiduspider
Allow: /
Crawl-delay: 2

User-agent: Googlebot
Allow: /
Crawl-delay: 1

3.2 使用模块动态生成(nuxt.config.ts)

robots: {
  rules: {
    UserAgent: '*',
    Allow: '/',
    Disallow: ['/admin/''/account/*''/api/*'],
    'Crawl-delay'2,
    Sitemap: 'https://your-domain.com/sitemap.xml'
  },
  // 环境区分配置
  enabled: process.env.NODE_ENV === 'production',
  // 开发环境配置
  dev: {
    rules: {
      UserAgent: '*',
      Disallow: '/'
    }
  }
}

四、验证与测试

4.1 本地测试

启动开发服务器后访问以下地址验证:

  • 站点地图:http://localhost:3000/sitemap.xml
  • 爬虫协议:http://localhost:3000/robots.txt

4.2 调试工具

利用Nuxt DevTools的SEO选项卡检查配置:

npm run dev -- --open

4.3 生产环境验证

部署后使用搜索引擎工具验证:

  • Google Search Console:https://search.google.com/search-console
  • 百度资源平台:https://ziyuan.baidu.com

五、高级配置选项

5.1 自定义站点地图样式

sitemap: {
  xsl: {
    tips: true// 显示提示信息
    columns: [
      { label: 'URL', width: '50%' },
      { label: 'Last Modified', width: '25%' },
      { label: 'Change Frequency', width: '15%' },
      { label: 'Priority', width: '10%' }
    ]
  }
}

5.2 缓存配置

sitemap: {
  cacheMaxAgeSeconds: 60 * 60 * 12// 12小时缓存
  runtimeCacheStorage: {
    type'redis',
    options: {
      host: 'localhost',
      port: 6379
    }
  }
}

5.3 国际化站点配置

如果使用nuxt-i18n模块:

sitemap: {
  autoI18n: true,
  i18n: {
    locales: ['zh-CN''en-US''ja-JP'],
    defaultLocale: 'zh-CN'
  }
}

六、常见问题解决

6.1 动态路由不显示

  • 确保API端点返回正确的URL格式
  • 检查nuxt.config.ts中是否正确配置sources
  • 开发环境可启用调试模式:
sitemap: {
  debug: true // 访问 /__sitemap__/debug 查看调试信息
}

6.2 站点地图过大

  • 使用多站点地图拆分URL
  • 启用分块功能:
sitemap: {
  sitemaps: true,
  defaultSitemapsChunkSize: 5000 // 每个文件5000个URL
}

6.3 robots.txt不生效

  • 确保没有同时使用静态文件和模块配置
  • 检查部署环境是否正确设置NODE_ENV=production
  • 验证文件路径是否正确(必须位于网站根目录)
阅读: 14 | 发布时间: 2025-08-20 15:14:38