楊育晟(Peter Yang)

嗨, 我叫育晟, 部落格文章主題包含了程式設計、財務金融及投資...等等,內容多是記錄一些學習的過程和心得,任何想法都歡迎留言一起討論。



Email: ycy.tai@gmail.com
LinkedIn: Peter Yang
Github: ycytai

如何建立網站的 sitemap,讓搜尋引擎找得到你的網站

sitemap 顧名思義就是一個網站的地圖,當我們把應用放到網路上後,希望別人能夠搜尋的到,這時候要仰賴搜尋引擎的幫忙,因為現今瀏覽網頁都是先透過入口網站再到達目的地,我們可以把自己網站的地圖(有些什麼 endpoint)整理好,提交給搜尋引擎,這時搜尋引擎就能夠爬我們的網頁,然後顯示在搜尋結果當中。

以下的步驟是某天需要建立部落格的 sitemap 時,詢問 chatgpt 得到的結果,整體流程簡單而且可以使用,因此留下這篇文章當紀錄XD,下方的例子是以 nextjs 當範例。

安裝需要的套件

npm install sitemap-generator

寫 script 產生 xml 檔

可以在專案的目錄中建立sitemap.js,記得要把 your-website-url.com 換成需要的網址。

// sitemap.js

const SitemapGenerator = require('sitemap-generator');
const path = require('path');

// Define the URL of your website
const baseUrl = 'https://your-website-url.com';

// Define the path where the sitemap will be saved
const outputPath = path.resolve(__dirname, 'public', 'sitemap.xml');

// Create a new instance of the SitemapGenerator
const generator = SitemapGenerator(baseUrl, {
  filepath: outputPath,
});

// Register event listeners for the generator
generator.on('done', () => {
  console.log(`Sitemap generated at ${outputPath}`);
});

// Start the generator
generator.start();

執行 script

node sitemap.js

next.config.js 中加入 sitemap

// next.config.js

module.exports = {
  // Other Next.js configurations...

  async rewrites() {
    return [
      // Other rewrites...

      // Add a rewrite for the sitemap
      {
        source: '/sitemap.xml',
        destination: '/_next/static/sitemap.xml',
      },
    ];
  },
};

npm run dev 跑起來,找到 sitemap

在 local 跑起來後,可以直接看到產生好的 sitemap http://127.0.0.1:3000/sitemap.xml,接著只要把這個網址再提交給搜尋引擎就 ok 哩。

Tags:
# sitemap
# nextjs
# google