LoginSignup
35
38

More than 5 years have passed since last update.

[Rails 4.1] sitemap-generator を使って Sitemap を作成する。

Posted at

はじめに

Rails4.1で作ったWeb ServicesのSEO対策で、sitemapを作りました。
毎週というか、ほぼ毎日本番デプロイをしていくフェーズなので、毎日sitemapを更新出来るようにしたいと思います。

Gemfile

以下を追記。

Gemfile
gem "sitemap_generator"

追記をしたら bundle install

$ bundle install

設定ファイルの生成

$ rake sitemap:install

/config/sitemap.rbが生成される。
ここにサイトマップに載せたいURL情報を記述

設定をする

config/sitemap.rb
# Set the host name for URL creation
SitemapGenerator::Sitemap.default_host = 'http://your_url.jp' # ホスト名
SitemapGenerator::Sitemap.sitemaps_path = 'sitemaps/' # 保存先(この場合 /public/sitemaps/以下になる)

# 以下にサイトマップに載せたいURLを設定していく
SitemapGenerator::Sitemap.create do
  # Put links creation logic here.
  #
  # The root path '/' and sitemap index file are added automatically for you.
  # Links are added to the Sitemap in the order they are specified.
  #
  # Usage: add(path, options={})
  #        (default options are used if you don't specify)
  #
  # Defaults: :priority => 0.5, :changefreq => 'weekly',
  #           :lastmod => Time.now, :host => default_host
  #
  # Examples:
  #
    add article_path, :priority => 0.7, :changefreq => 'daily'
    add ranking_path, :priority => 0.7, :changefreq => 'weekly'

    Product.find_each do |product|
      add product_path(product), :lastmod => product.updated_at
      Kuchikomi.find_each do |kuchikomi|
        add product_kuchikomi_path(product.id,kuchikomi), :lastmod => kuchikomi.updated_at
      end
      Evaluation.find_each do |eval|
        add product_evaluation_path(product.id,eval), :lastmod => eval.created_at
      end
    end

end

登録/更新

$ rake sitemap:refresh

指定した場所(デフォルトではpublic直下)にsitemap.xml.gzという圧縮ファイルが生成される。
解凍するとsitemap.xmlを確認できる。

これで googleやBingとかに登録してくれます。
詳しくはGitHubを御覧ください。

cron

更新cronとかで適宜必要な頻度で上記のコマンドを叩ける様に設定する。

heroku

herokuアプリの場合、
heroku schedulerを使って、
rake sitemap:rehashを登録。

これでcronが回って登録可能。

35
38
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
35
38