LoginSignup
29
26

More than 5 years have passed since last update.

Middlemanでsitemap.xmlを生成する

Last updated at Posted at 2014-01-13

builderでXML構築

Middlemanをつかっていて、sitemap.xmlを生成したいと思ったのでいろいろ調べて試してみました。大まかな方針は、builderを使ってsitemapから必要なものを取り出してXMLを生成します。

まず、 Gemfile に下記1行を追加して bundle install します。

gem 'builder'

次に、 source/sitemap.xml.builder を作成し、下記追加します。 http://example.com の部分は各自の環境に合わせて変更してください。

---
layout: false
---
xml.instruct!
xml.urlset "xmlns" => "http://www.sitemaps.org/schemas/sitemap/0.9" do
  sitemap.resources.each do |resource|
    xml.url do
      xml.loc "http://example.com#{resource.url}"
    end if resource.destination_path =~ /\.html$/
  end
end

上記の方法で、 *.html ファイルのみを対象に sitemap.xml を生成できます。あとは Search Console で設定してあげると完了です。

応用例

これで必要最低限のものはそろっています。ほかにフィールドを追加したければ少し工夫が必要です。

lastmod

必須フィールドではないのでなくてもいいですが、クローラーに更新を伝えるために指定しておきたい気がします。

xml.lastmod File.mtime(resource.source_file).strftime('%Y-%m-%d')

上記のようにすると、ファイルの更新日時のタイムスタンプが入ります。ただ、自分の場合はgit管理していて、他のマシンでpullするとずれてしまいます。ここはFrontmatterで指定するのがいい気がします。

---
modifiy_date: 2014-01-13
---

上記のような感じで追加しておき、

lastmod = resource.data.modify_date.presence || resource.data.date.presence
xml.lastmod lastmod if lastmod.present?

のようにしておくと、 modify_date を見て、ない場合は date が入り、それもない場合は lastmod 要素自体が生成されなくなります。

changefreq / priority

ぼくは changefreqpriority を指定するために、ファイル名のパターンを定義しておいて、マッチすればその値を書き出すようにしています。たとえば以下のような感じです。

changefreqs = {
  'index.html' => :weekly,
  /^mono\// => :daily
}
# :
# : 中略
# :
changefreqs.each do |file, freq|
  next if file.kind_of?(String) && resource.destination_path != file
  next if file.kind_of?(Regexp) && resource.destination_path !~ file
  xml.changefreq freq.to_s
  break
end

全文はGithubにあげているので参照してみてください。もっといい方法があればコメントでおしえてください!

参考文献

29
26
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
29
26