⚠️ Alpha内测版本警告:此为早期内部构建版本,尚不完整且可能存在错误,欢迎大家提Issue反馈问题或建议
Skip to content

12.2.4 给爬虫画地图——站点地图:XML Sitemap 生成与提交

一句话破题

站点地图是一份告诉搜索引擎"我的网站有哪些页面、哪些更重要、多久更新一次"的清单,帮助爬虫更高效地发现和抓取你的内容。

核心价值

站点地图对 SEO 的作用:

  1. 加速收录:主动告知搜索引擎新页面的存在
  2. 优先级指引:告诉爬虫哪些页面更重要
  3. 更新频率:帮助爬虫决定多久来一次
  4. 覆盖盲区:确保没有内链指向的"孤岛页面"也能被发现

本质还原:Sitemap 的结构

xml
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>https://example.com/</loc>
    <lastmod>2024-01-15</lastmod>
    <changefreq>daily</changefreq>
    <priority>1.0</priority>
  </url>
  <url>
    <loc>https://example.com/blog/nextjs-tutorial</loc>
    <lastmod>2024-01-10</lastmod>
    <changefreq>weekly</changefreq>
    <priority>0.8</priority>
  </url>
</urlset>
字段含义建议值
loc页面 URL(必填)使用绝对路径
lastmod最后修改时间ISO 8601 格式
changefreq更新频率always/hourly/daily/weekly/monthly/yearly/never
priority相对优先级0.0-1.0,首页通常为 1.0

Next.js 中生成站点地图

方法一:静态站点地图

tsx
// app/sitemap.ts
import { MetadataRoute } from 'next';

export default function sitemap(): MetadataRoute.Sitemap {
  return [
    {
      url: 'https://example.com',
      lastModified: new Date(),
      changeFrequency: 'daily',
      priority: 1,
    },
    {
      url: 'https://example.com/about',
      lastModified: new Date(),
      changeFrequency: 'monthly',
      priority: 0.8,
    },
  ];
}

方法二:动态站点地图

tsx
// app/sitemap.ts
import { MetadataRoute } from 'next';
import { getAllPosts } from '@/lib/posts';

export default async function sitemap(): MetadataRoute.Sitemap {
  const posts = await getAllPosts();
  
  const postUrls = posts.map((post) => ({
    url: `https://example.com/blog/${post.slug}`,
    lastModified: new Date(post.updatedAt),
    changeFrequency: 'weekly' as const,
    priority: 0.7,
  }));

  return [
    {
      url: 'https://example.com',
      lastModified: new Date(),
      changeFrequency: 'daily',
      priority: 1,
    },
    ...postUrls,
  ];
}

访问 /sitemap.xml 即可看到生成的站点地图。

大型网站:Sitemap Index

当页面数量超过 50,000 或文件大小超过 50MB 时,需要使用站点地图索引:

xml
<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <sitemap>
    <loc>https://example.com/sitemap-posts.xml</loc>
    <lastmod>2024-01-15</lastmod>
  </sitemap>
  <sitemap>
    <loc>https://example.com/sitemap-products.xml</loc>
    <lastmod>2024-01-14</lastmod>
  </sitemap>
</sitemapindex>

提交站点地图

  1. 在 robots.txt 中声明
txt
Sitemap: https://example.com/sitemap.xml
  1. 通过站长工具提交
    • Google Search Console
    • 百度站长平台
    • Bing Webmaster Tools

AI 协作指南

  • 核心意图:让 AI 帮你生成站点地图配置或解决站点地图问题。
  • 需求定义公式"请帮我在 Next.js 中实现动态站点地图,需要包含所有博客文章和产品页面,使用数据库中的更新时间作为 lastmod。"
  • 关键术语sitemap.xmlMetadataRoute.SitemapSitemap Indexlastmod

避坑指南

  • 只包含可索引页面:不要把 404 页面、登录后页面放入站点地图。
  • 保持 lastmod 准确:不要把所有页面的 lastmod 设为当前时间,这会降低信息的可信度。
  • 定期更新:站点地图应该随着内容更新而更新。
  • 监控爬取状态:在站长工具中检查站点地图是否被正确读取。