给 eleventy(11ty) 添加 sitemap.xml 和 robots.txt

配置过程

  1. 添加数据文件 _data/site.json,写入以下内容,定义站点信息和 sitemap 中的一些默认值:
1
2
3
4
5
6
7
8
9
{
"baseUrl": "https://xiaobot.osguider.com",
"robots": "/robots.txt",
"sitemap": {
"path": "sitemap.xml",
"changefreq": "daily",
"priority": 0.5
}
}
  1. 添加 sitemap 模板文件,写入以下内容:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
---
permalink: "{{ site.sitemap.path }}"
eleventyExcludeFromCollections: true
---
<?xml version="1.0" encoding="UTF-8"?>

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
{% for page in collections.all %}
{% unless page.data.sitemap.ignore %}
<url>
<loc>{{ site.baseUrl }}{{ page.url | url }}</loc>
<lastmod>{{ page.date | date: '%Y-%m-%dT%H:%M:%S.%LZ' }}</lastmod>
<changefreq>{{ site.sitemap.changefreq }}</changefreq>
<priority>{{ page.data.sitemap.priority | default: site.sitemap.priority | default: 0.5 }}</priority>
</url>
{% endunless %}
{% endfor %}
</urlset>
  1. 【可选】配置不同页面的 sitemap 表现:

    • 如果不希望某些页面在被包含在 sitemap 文件中,在页面元数据中添加 sitemap.ignore: true 即可;
    • 可以对不同的页面设置不同的 sitemap 优先级,在页面元数据中添加 sitemap.priority: 0.5,取值范围 0-1;
    • 对于分页数据,要设置 pagination.addAllPagesToCollections: true 才会在 sitemap.xml 文件中包含每一个分页页面。
  2. 添加模板文件 src/robots.txt,写入以下内容:

1
2
3
4
5
6
7
8
9
---
eleventyComputed:
permalink: "{{ site.robots }}"
eleventyExcludeFromCollections: true
---
Sitemap: {{ site.baseUrl }} {{ site.sitemap.path }}

User-agent: *
Disallow:

重新编译,over!

参考文档

  • How to create sitemap.xml
  • Sitemap xml
  • liquid
  • sitemap format