Sitemap.xml on Heroku with Ruby on Rails

Steps to generate dynamic sitemap.xml for Ruby on Rails site hosted on Heroku.

1) Remove /public/sitemap.xml if it exists.

2) Add following to routes.rb


resources :sitemaps, :only => :show
get "sitemap" => "sitemaps#show"

3) Create sitemaps controller


 rails g controller sitemaps

4) Update SitemapsController with following code


class SitemapsController 
  def show
    @posts = Post.where(:active => true) #we are generating url's for posts
    respond_to do |format|
     format.xml
    end
  end
end

5) Create /app/views/sitemap/index.xml.builder with the following content.


base_url = "http://#{request.host_with_port}"
xml.instruct! :xml, :version=>'1.0'
xml.tag! 'urlset', 'xmlns' => 'http://www.sitemaps.org/schemas/sitemap/0.9' do
  xml.url{
      xml.loc("http://example.com")
      xml.changefreq("weekly")
      xml.priority(1.0)
  }
  xml.url{
      xml.loc("http://example.com/posts")
      xml.changefreq("daily")
      xml.priority(0.9)
  }
  @posts.each do |p|
    xml.url {
      xml.loc("http://example.com/#{p.id.to_s}")
      xml.changefreq("weekly")
      xml.priority(0.5)
    }
  end
end

5) Commit and upload to heroku.

Advertisements