Next-Sitemap 项目完整配置示例详解
项目背景
Next-Sitemap 是一个专为 Next.js 应用设计的站点地图生成工具,能够自动为你的 Next.js 网站生成符合搜索引擎规范的 sitemap.xml 和 robots.txt 文件。这对于 SEO 优化至关重要,能帮助搜索引擎更好地抓取和索引你的网站内容。
完整配置解析
下面我们将详细解析 Next-Sitemap 的所有可用配置选项,帮助你全面掌握这个工具的强大功能。
基础配置
module.exports = {
siteUrl: 'https://example.com',
changefreq: 'daily',
priority: 0.7,
sitemapSize: 5000,
generateRobotsTxt: true,
}
- siteUrl: 你的网站基础URL,这是必填项
- changefreq: 建议搜索引擎抓取频率,可选值有 always/hourly/daily/weekly/monthly/yearly/never
- priority: 页面优先级(0.0-1.0),表示该页面在你网站中的重要程度
- sitemapSize: 单个sitemap文件包含的最大URL数量,超过将自动分片
- generateRobotsTxt: 是否自动生成robots.txt文件
排除特定页面
exclude: ['/protected-page', '/awesome/secret-page'],
通过exclude数组可以指定不希望出现在sitemap中的页面路径,常用于后台管理页面或隐私内容。
多语言支持
alternateRefs: [
{
href: 'https://es.example.com',
hreflang: 'es',
},
{
href: 'https://fr.example.com',
hreflang: 'fr',
},
],
alternateRefs配置用于多语言网站,为每个URL指定不同语言版本的替代链接,帮助搜索引擎理解不同语言版本间的关系。
自定义转换函数
transform: async (config, path) => {
return {
loc: path,
changefreq: config.changefreq,
priority: config.priority,
lastmod: config.autoLastmod ? new Date().toISOString() : undefined,
alternateRefs: config.alternateRefs ?? [],
}
},
transform函数允许你完全控制每个URL在sitemap中的表现方式,可以基于不同路径设置不同的抓取频率、优先级等。
添加额外路径
additionalPaths: async (config) => [
await config.transform(config, '/additional-page'),
],
对于Next.js自动路由系统之外的页面,可以使用additionalPaths手动添加到sitemap中。
robots.txt高级配置
robotsTxtOptions: {
policies: [
{
userAgent: '*',
allow: '/',
},
{
userAgent: 'test-bot',
allow: ['/path', '/path-2'],
},
{
userAgent: 'black-listed-bot',
disallow: ['/sub-path-1', '/path-2'],
},
],
additionalSitemaps: [
'https://example.com/my-custom-sitemap-1.xml',
'https://example.com/my-custom-sitemap-2.xml',
'https://example.com/my-custom-sitemap-3.xml',
],
},
robotsTxtOptions提供了细粒度的robots.txt控制能力:
-
policies: 定义不同爬虫的访问规则
- userAgent指定目标爬虫(*表示所有)
- allow/disallow控制访问权限
-
additionalSitemaps: 添加额外的sitemap引用
生成结果示例
基于上述配置,Next-Sitemap将生成以下标准的robots.txt文件:
# *
User-agent: *
Allow: /
# test-bot
User-agent: test-bot
Allow: /path
Allow: /path-2
# black-listed-bot
User-agent: black-listed-bot
Disallow: /sub-path-1
Disallow: /path-2
# Host
Host: https://example.com
# Sitemaps
Sitemap: https://example.com/sitemap.xml # Index sitemap
Sitemap: https://example.com/my-custom-sitemap-1.xml
Sitemap: https://example.com/my-custom-sitemap-2.xml
Sitemap: https://example.com/my-custom-sitemap-3.xml
最佳实践建议
- 合理设置changefreq:根据内容更新频率设置,过于频繁但实际不更新会影响爬虫信任度
- 优先级分配:首页设为1.0,重要内容页0.7-0.9,次要内容0.3-0.5
- 大网站使用sitemap分片:当URL超过5000时自动分片,也可手动设置更小的分片大小
- 定期更新lastmod:特别是内容频繁变更的页面
- 保护敏感内容:确保后台、API路由等不被索引
通过合理配置Next-Sitemap,你可以显著提升网站在搜索引擎中的表现,让重要内容更容易被发现和索引。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考