Astro Sitemap 設定:如何排除 noindex、分頁與不該送出的路徑
Astro 的 sitemap 不需要手寫 XML,但「有產生」不代表每個 URL 都應該送進搜尋引擎。靜態站很常同時有文章頁、標籤頁、archive、分頁或 redirect fallback;其中一部分可能已經 noindex,若仍出現在 sitemap,反而會讓索引訊號互相矛盾。
本文以目前 @astrojs/sitemap 的建置行為整理設定原則。直接答案是:在 astro.config.mjs 設定正確的 site,並用 sitemap 的 filter 排除 noindex、archive 與非 canonical 的分頁 URL;建置後只提交 sitemap index 給 robots.txt 或 Search Console。
安裝與基本設定
官方整合在 build 時掃描靜態產生的 routes,輸出 sitemap-index.xml 與一個或多個 sitemap 檔。先安裝:
pnpm astro add sitemap接著確認 site 是正式站的 HTTPS 網址,且與部署的 canonical 網域一致:
import sitemap from '@astrojs/sitemap';import { defineConfig } from 'astro/config';
export default defineConfig({ site: 'https://example.com/', integrations: [sitemap()],});site 不只是 sitemap 的基底網址;站內 canonical、RSS 或其他產物也常依賴它。不要用本機網址或 staging 網域建置正式產物。
用 filter 對齊 noindex 策略
最實用的設定,是把「不希望被索引」的 route 同步排除在 sitemap 外。例如這個部落格把 archive、所有 tag 頁與第二頁以後的分頁設為 noindex,filter 也採用同樣規則:
sitemap({ filter: (page) => !page.includes('/tags/') && !page.includes('/archive/') && !/\/\d+\/$/.test(new URL(page).pathname),}),filter 收到的是完整 URL,因此以 new URL(page).pathname 判斷分頁會比直接比對字串穩妥。你的網站如果採用不同的分頁路徑或語系路徑,規則也要跟著調整;不要直接複製這個正規表示式。
robots.txt 只需要指向 sitemap index
建置後,輸出目錄會有 sitemap-index.xml,其內容會列出實際 sitemap 檔案。robots.txt 只需要提供 index 的完整網址:
User-agent: *Allow: /
Sitemap: https://example.com/sitemap-index.xml不必把 sitemap link 手動塞進每一頁的 <head>;搜尋引擎可經由 robots.txt 或 Search Console 取得 sitemap。重要的是確認這個網址在正式網域回傳 200,沒有被 redirect、登入或快取設定意外攔住。
每次改路由後的驗證方式
執行建置後,直接檢查輸出內容:
pnpm buildrg -n 'archive|/tags/|/2/' dist/sitemap*.xml第二個指令理想上沒有輸出;如果有,先確認它是否真的是應該索引的頁面,再調整 route 或 filter。也可以用:
curl -I https://example.com/sitemap-index.xml確認正式站回傳正確狀態與內容型別。發現 Search Console 報「已提交 URL 被 noindex」時,不要只在 Search Console 重送 sitemap;先修正 sitemap filter 或頁面的 robots meta,讓兩邊的宣告一致。
這次更新的重點
Astro sitemap 的工作是列出希望被探索的 canonical URL,而不是列出所有可以開啟的 route。把 filter 與 noindex 規則一起維護,才能避免 archive、tag 或分頁頁面持續回到 sitemap。
參考資料:
回報錯字、失效連結,或告訴我你想看的延伸主題。