@astrojs/sitemapを使ってAstroサイトのサイトマップを生成する
基本的な使い方
パッケージをインストールします。
npm install @astrojs/sitemap
astro.config.mjsにインポート、site・integrationsを設定します。
astro.config.mjs
import { defineConfig } from 'astro/config';
import sitemap from '@astrojs/sitemap';
export default defineConfig({
site: "site: "https://xxx.com", //ドメイン・末尾スラッシュなし
integrations: [sitemap()],
});
特定のURLを追加する
customPagesに配列でURLを指定します。
astro.config.mjs
export default defineConfig({
//~
integrations: [sitemap({
customPages: [
"https://xxx.com/yyy/",
"https://xxx.com/yyy/zzz/",
]
})],
});
追加したURLはどのような順番で記述される?
サイトマップ内のURLの記述の順番がSEOに影響することはありませんが、どのような順番で出力されるか試してみました。
結論
_(アンスコ)、-(ハイフン)、0-9a-zA-Zの順に出力される。
数字のみだと数字として判断し、数字+文字列だと文字となるけど、「数字のみ」→「数字+文字列」でまとまって出力されるわけではないようです。
以下はcustomPagesの配列で指定した場合の出力結果です。
<url><loc>https://xxx.com/0/</loc></url>
<url><loc>https://xxx.com/00/</loc></url>
<url><loc>https://xxx.com/0hoge/</loc></url>
<url><loc>https://xxx.com/1/</loc></url>
<url><loc>https://xxx.com/01/</loc></url>
<url><loc>https://xxx.com/1hoge/</loc></url>
<url><loc>https://xxx.com/2hoge/</loc></url>
<url><loc>https://xxx.com/11/</loc></url>
<url><loc>https://xxx.com/99/</loc></url>
<url><loc>https://xxx.com/111/</loc></url>
この場合どうなる?
- /recruit/をcustomPagesに追加したとき
- /form/complete/をcustomPagesに追加したとき
- すでに存在する/form/error/を追加したとき
.
└── src/
└── pages/
├── about/
│ └── index.astro
└── form/
├── index.astro
├── thanks.astro
└── error.astro
1. /recruit/をcustomPagesに追加したとき
a-zA-Zの順に則って一番最後に追加されました。
2. /form/complete/をcustomPagesに追加したとき
form/とform/error/の間に追加されました。
3. すでに存在する/form/error/を追加したとき
重複登録・追加されませんでした。
特定のURLを除外する
filterに条件を設定します。
astro.config.mjs
export default defineConfig({
//~
integrations: [sitemap({
filter: (page) => page !== 'https://xxx.com/hoge/',
})],
});
includes/matchメソッドでまとめて除外する
URLの一部に含まれているかどうかで判定されるので、/hogeを除外すると/hoge/hogeも除外されます。
特定の階層やURLを除外する場合は、完全一致またはドメインから指定するといいでしょう。
// /hogeが含まれるURLを除外
filter: (page) => !page.includes("/hoge"),
// /hogeと/errorが含まれるURLを除外
filter: (page) =>
!page.includes("/hoge") &&
!page.includes("/error")
// /hoge/数字のみ/が含まれるURLを正規表現で除外
filter: (page) => !page.match(/\/hoge\/[0-9]+\//),
filterとcustomPagesどちらが優先?
customPagesに追加したURLをfilterで除外設定をすると、filterが優先されURLが追加されませんでした。