使用nodejs動態生成網站sitemap.xml 優化抓取 —— SEO優化 原

主要講一下如何用Nodejs + express + sitemap.js 來動態生成 sitemap.xml。 自己的博客前端動態生成 sitemap.xml 來讓搜索引擎(google_site:diamondfsd.com)抓取,生成了 sitemap.xml 過後,果然自己博客的收錄速度快了很多。
下面就簡單的介紹一下 sitemap.xml 的作用以及 一個簡單的例子。

sitemap 介紹

sitemap,翻譯過來就是站點地圖。是告訴搜索引擎這個網站上有那些頁面可以抓取。
sitemap最簡單的格式 txt 格式, 只需要每行列出一個鏈接就可以: sitemap.txt

https://diamondfsd.com/xxx/xxx
https://diamondfsd.com/xxx/xxx
.......

另外一種比較豐富的格式就是xml格式,xml格式由 <urlset></urlset> 作爲根元素,內嵌多個<url></url> 子元素
https://diamondfsd.com/sitemap.xml

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" 
xmlns:news="http://www.google.com/schemas/sitemap-news/0.9"
xmlns:xhtml="http://www.w3.org/1999/xhtml" 
xmlns:mobile="http://www.google.com/schemas/sitemap-mobile/1.0" 
xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">
  <url>
    <loc>
      http://diamondfsd.com/article/0514fe5c-3925-4175-9486-940c0ee9c054
    </loc>
    <lastmod>2017-01-14</lastmod>
    <changefreq>daily</changefreq>
  </url>
  <url>
    <loc>
      http://diamondfsd.com/article/35caae5b-78f5-4728-9170-92144570c7a3
    </loc>
    <lastmod>2017-01-22</lastmod>
    <changefreq>daily</changefreq>
  </url>
</urlset>

[Sitemap] XML格式標籤定義

標籤參數描述
<urlset>必須屬性內寫了當前使用的協議標準
<url>必須每個url條目的父標籤,內包含了url的一些其他信息描述
<loc>必須網頁的網址(網址以協議開頭 http:// [https://]
<lastmod>可選網頁的最後一次修改時間,使用W3C的時間標準,例如 YYYY-MM-DD
<changefreq>可選網頁的更新頻率,可以供搜索引擎參考抓取頻率 always, hourly, daily, weekly, monthly, yearly, never(搜索引擎的會有自己的抓取策略,所以這個值僅供搜索引擎參考)
<priority>可選優先級取值範圍 0.1 至 1。 ----- 也是一個供搜索引擎參考的值

如何動態生成sitemap.xml 文件

毫無疑問,sitemap.xml 擁有更豐富的語義,可以更好的讓搜索引擎抓取。本博客使用的sitemap.js 來生成 sitemap.xml 文件。

import express from 'express'
import sm from 'sitemap'
import service from  './service/ArticleService'

const app = express()
const host = 'https://diamondfsd.com'

/* service.allNames 獲取一個文章list 結構如下
*  {
      title: String,
      id: String,
      updateTime: Long
    }
*/

app.get('/sitemap.xml', (req, res) => {
  service.allNames().then(data => {
    let smOption = {
      hostname: host,
      cacheTime: 600000,
      urls: [host]
    }
    data.forEach(art => {
      smOption.urls.push({
        url: `/article/${art.id}`,
        changefreq: 'daily',
        lastmod: new Date(art.updateTime)
      })
    })
    let xml = sm.createSitemap(smOption).toString()
    res.header('Content-Type', 'application/xml')
    res.send(xml)
  }).catch(e => {
    res.send(e)
  })
})

具體的文檔,可以去 ekalinin/sitemap.js 去看,這裏只說一下本博客中的實際使用。 我將所有的文章的id以及更新時間獲取到,然後生成 url 對象

{
  url: `/article/${article.id}`,
  changefreq: 'daily',
  lastmod: new Date(art.updateTime)  
}

然後構成 創建sitemap.xml 所需要的 對象

{
     hostname: host,
     cacheTime: 600000,
     urls: [url, url, url, url...]
}

最後用 sitemapcreateSitemap(opt).toString() 方法獲得 xml 字符串 然後發送到客戶端。

每次搜索引擎請求https://diamondfsd.com/sitemap.xml的時候,就會獲取最新的文章列表,然後生成最新的sitemap.xml。 這樣能夠讓搜索引擎更快,跟全面的獲取到網站想要被抓取的網頁地圖。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章