Ruby on Rails Sitemap Generator

Dec 20, 2011 Published by Tony Primerano

How to build a sitemap for your rails app.

This wiki entry was the basis for my sitemap recipe in Advanced Rails Recipies

Related blog posts

The following example will build a sitemap for a single model but it can easily be extended.


  • Build a controller for your sitemap
    • script/generate controller sitemap
  • query model for information that you want in the sitemap
class SitemapController < ApplicationController
  def sitemap
    @entries = YourModel.find(:all, :order => "updated_at DESC", :limit => 50000)
    headers["Content-Type"] = "text/xml"
    # set last modified header to the date of the latest entry.
    headers["Last-Modified"] = @entries[0].updated_at.httpdate    
  • Create your sitemap.rxml file
xml.urlset "xmlns" => "" do
  @entries.each do |entry|
    xml.url do
      xml.loc url_for(:controller => 'controller you use to show the model', 
                      :action => 'show', 
                      :id =>,
                      :only_path => false)
      xml.lastmod entry.updated_at.to_date
only_path => false is necessary as sitemaps are required to have protocol and domain.


  • Update your routes file to allow your sitemap to live in the root directory
    • ex: map.connect 'sitemap.xml', :controller => "sitemap", :action => "sitemap"

using a sitemap index

If you have over 50000 URLs you need to use a sitemap index file. I'll put an example here eventually.  ;-)