Generate a XML-Sitemap for Google with Ruby on Rails

If you provide a sitemap of your webpage, then it is easier for searchengines to crawl your whole page. You can either create an xml-sitemap or a txt-sitemap.

txt sitemap

A txt sitemap is a simple list of all your pages that searchengines should crawl


xml sitemap

With an xml sitemap you can provide more details about every page. You can specify for example the change frequency of a webpage or the date of the last modification of the page. You can help searchengines like google to understand and properly crawl your page.


<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="">

how to generate a sitemap in ruby on rails

First we need a route for our sitemaps.


get "sitemap" => "pages#sitemap"

Next we have to select all necessary data that we need to generate all pages.
We can tell the controller, that we want to respond to both formats: xml and txt.
In both cases we don't need a layout as we only want to return text.


def sitemap
    @posts = Post.where(:published => true)
    respond_to do |format|
        format.xml { render layout: false }
        format.txt { render layout: false }

For our xml sitemap we can write an xml builder in the view


xml.instruct! :xml, :version => "1.0"
xml.urlset "xmlns" => "" do
  for post in @posts do
    xml.url do
      xml.loc post_url(post)
      xml.lastmod post.updated_at.to_date
      xml.changefreq "monthly"
      xml.priority "0.5"

Our txt-sitemap is even easier


<% for post in @posts do %>
<%= post_url(post) %>
<% end %>

Now we only need to tell the search engine bots, where they can find the sitemaps. One easy solution is to add a line in the robots.txt file.


Sitemap: /sitemap.xml
Sitemap: /sitemap.txt
comments powered by Disqus