Railsでサイトマップ(sitemap.xml)を作りたい

Railsでサイトマップを作るには、sitemap_generator というgemを使うのが便利です。

  • Gemfileに下記の内容を追加します。
Gemfile
gem 'sitemap_generator'
  • bundle install を実行します。
bundle_install
% bundle install

* rake sitemap:install コマンドを実行すると、config/sitemap.rb ファイルが生成されます。

rake_sitemap:installコマンド
% rake sitemap:install
created: config/sitemap.rb

* デフォルトのconfig/sitemap.rbには、下記の内容が書かれています。

config/sitemap.rb
# Set the host name for URL creation
SitemapGenerator::Sitemap.default_host = "http://www.example.com"
 
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 '/articles'
  #
  #   add articles_path, :priority => 0.7, :changefreq => 'daily'
  #
  # Add all articles:
  #
  #   Article.find_each do |article|
  #     add article_path(article), :lastmod => article.updated_at
  #   end
end
  • このファイルを下記のように書き換えます。(この例では、Productモデルの全データのURLを登録する処理をしています。)
config/sitemap.rb
# Set the host name for URL creation
SitemapGenerator::Sitemap.default_host = "http://サイトのURL"
 
SitemapGenerator::Sitemap.create do
  Product.find_each do |product|
    add product_path(product), :lastmod => product.updated_at
  end
end
  • rake sitemap:refresh を実行します。
% rake sitemap:refresh
In 'sampleapp/public/':
+ sitemap.xml.gz                                          14 links /  464 Bytes
Sitemap stats: 14 links / 1 sitemaps / 0m00s

Pinging with URL 'http://example.com/sitemap.xml.gz':
  Successful ping of Google
  Successful ping of Bing
  • これで、public/sitemap.xml.gz が作成されます。
コメントを入力:
U M D L B