網站地圖是與 Google 溝通最簡單的方式。它們指出屬於您網站的網址以及它們的更新時間,以便 Google 可以輕鬆偵測新內容並更有效率地抓取您的網站。
即使 XML 網站地圖是最廣為人知和使用的一種,它們也可以透過 RSS 或 Atom 建立,如果您喜歡極簡的方式,甚至可以透過 文字 檔案建立。
網站地圖是一個檔案,您可以在其中提供有關網站上的網頁、影片和其他檔案以及它們之間關係的資訊。Google 等搜尋引擎會讀取此檔案,以便更智慧地抓取您的網站。
根據 Google 的說法
您可能在以下情況下需要網站地圖:
雖然網站地圖並非獲得良好搜尋引擎效能的必要條件,但它們可以促進機器人抓取和索引,因此您的內容將會被更快地擷取並相應地排名。
強烈建議使用網站地圖,並在您的網站上發佈新內容時動態更新它們。靜態網站地圖也是有效的,但它們對 Google 的用處可能較小,因為它們無法持續用於探索新內容。
有兩個選項
如果您有一個相對簡單且靜態的網站,您可以手動在專案的 public
目錄中建立一個 sitemap.xml
檔案
<!-- public/sitemap.xml -->
<xml version="1.0" encoding="UTF-8">
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>http://www.example.com/foo</loc>
<lastmod>2021-06-01</lastmod>
</url>
</urlset>
</xml>
您的網站更有可能是動態的。在這種情況下,我們可以利用 getServerSideProps
按需產生 XML 網站地圖。
我們可以在 pages 目錄中建立一個新頁面,例如 pages/sitemap.xml.js
。此頁面的目標是訪問我們的 API 以取得資料,讓我們知道動態頁面的網址。然後,我們將編寫一個 XML 檔案作為 /sitemap.xml 的回應
以下是一個您可以自己嘗試的範例
//pages/sitemap.xml.js
const EXTERNAL_DATA_URL = 'https://jsonplaceholder.typicode.com/posts';
function generateSiteMap(posts) {
return `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<!--We manually set the two URLs we know already-->
<url>
<loc>https://jsonplaceholder.typicode.com</loc>
</url>
<url>
<loc>https://jsonplaceholder.typicode.com/guide</loc>
</url>
${posts
.map(({ id }) => {
return `
<url>
<loc>${`${EXTERNAL_DATA_URL}/${id}`}</loc>
</url>
`;
})
.join('')}
</urlset>
`;
}
function SiteMap() {
// getServerSideProps will do the heavy lifting
}
export async function getServerSideProps({ res }) {
// We make an API call to gather the URLs for our site
const request = await fetch(EXTERNAL_DATA_URL);
const posts = await request.json();
// We generate the XML sitemap with the posts data
const sitemap = generateSiteMap(posts);
res.setHeader('Content-Type', 'text/xml');
// we send the XML to the browser
res.write(sitemap);
res.end();
return {
props: {},
};
}
export default SiteMap;