Generating a sitemap.xml file on Heroku with Ruby on Rails

Here is a description of how to dynamically generate an xml sitemap every time it is accessed. If you have a larger site, you may want to generate the sitemap using a cron job, and publish it to a storage service like Amazon S3.

Step 1:
Remove /public/sitemap.xml if it exists.

Step 2:
Add the following to /config/routes.rb
get “sitemap.xml” => “sitemap#index”, as: “sitemap”, defaults: { format: “xml” }
Step 3:
Create /app/controllers/sitemap_controller.rb


 class SitemapController < ApplicationController
   def index
     @static_pages = [root_url, about_url, contact_url, help_url]
     @users = User.all
     @posts = Post.all
     respond_to do |format|
       format.xml
     end
   end
 end
 

Step 4:
Create /app/views/sitemap/index.xml.builder with the following content. Note that this sitemap.xml includes not only the links to the pages in the site, but also the links to the photographs that are embedded in the links, and which are stored on Amazon S3.


xml.instruct!
xml.urlset(
  'xmlns'.to_sym => "http://www.sitemaps.org/schemas/sitemap/0.9",
  'xmlns:image'.to_sym => "http://www.google.com/schemas/sitemap-image/1.1"
) do
  @static_pages.each do |page|
    xml.url do
      xml.loc "#{page}"
      xml.changefreq("monthly")
    end
  end
  @users.each do |user|
    xml.url do
      xml.loc "#{user_url(user)}"
      xml.changefreq("monthly")
    end
  end
  @posts.each do |post|
    xml.url do
      xml.loc "#{post_url(post)}"
      xml.lastmod post.updated_at.strftime("%F")
      xml.changefreq("monthly")
      if post.photo?
        xml.image :image do
          xml.image :loc, "#{request.protocol}#{request.host_with_port}#{post.photo(:medium)}"
        end
      end
    end
  end
end

Step 5:
Commit and upload to heroku.

Enjoy!

About Tom Slykhouse

Helping organizations apply technology to improve marketing results.

Connect with me on Google+