-
安装
next-sitemap
套件npm install next-sitemap
-
在
next.config.js
中加入next-sitemap
套件的設定// next.config.js const withSitemap = require('next-sitemap')({ // 在這裡設定 sitemap 的組態 // 詳細參考套件文件:https://github.com/iamvishnusankar/next-sitemap }) module.exports = withSitemap({ // 接著再加上原本 next.js 的設定 // ... })
-
編寫 sitemap 的設定檔
// sitemap.config.js module.exports = { // sitemap 的基本設定 siteUrl: 'https://www.example.com', // 網站的網址 changefreq: 'daily', // 告訴搜尋引擎更新頻率 priority: 0.7, // 告訴搜尋引擎網頁的重要性 generateRobotsTxt: true, // 是否產生 robots.txt exclude: [ // 不要列入 sitemap 的頁面 '/admin/**', '/dashboard/**', '/login', ], // 可以覆寫套件預設設定 robotsTxtOptions: { additionalSitemaps: [ // 其他 Sitemap 的網址 'https://www.example.com/sitemap-products.xml', 'https://www.example.com/sitemap-blog.xml', ] }, // sitemap 資訊 sitemapSize: 5000, gzip: true, }
-
在
package.json
設定要執行的 script{ "script": { "build": "next build && next-sitemap", // 注意順序,必須先 build,再執行 next-sitemap 進行生成 // 也可以在 next build 時加入 sitemap 的設定,這樣可以不需要這行 } }
-
執行
npm run build
,生成 sitemap會生成名為
sitemap.xml
,以及與sitemap.config.js
名稱相同的sitemap-xxx.xml.gz
,xxx 是由時間戳記生成。如果 sitemap 設定了
generateRobotsTxt: true
,那麼同時還會生成robots.txt
。
完成後就可以正常更新sitemap.xml文件以及robots.txt文件了。