Adding a sitemap to a rails 4 project

June 22, 2018

With every website we roll out, we get just a little bit better with SEO. One surprisingly effective but not often used trick for getting more google love is to submit a sitemap via Google Webmaster Tools. Not familiar? Grab a beer, leave this website, and go do your homework. You're back now? Sweet. Let's talk through adding a sitemap to our Rails 4 project. It's super easy and will take you just a few minutes. Step 1: Update your routes.rb: get 'sitemap.xml', :to => 'sitemap#index', :defaults => { :format => 'xml' } Step2: Add your controller. Each sitemap will be a little different but you can see that we're actually listing all of the notes (from this site) in our sitemap class SitemapController < ApplicationController layout nil def index headers['Content-Type'] = 'application/xml' respond_to do |format| format.xml { @notes = Note.where("published = true") } end end end Step 3: Add your sitemap folder and index.xml.erb file in the views folder. Once this is done, the sitemap will be viewable at http:///sitemap.xml <?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"><url><loc><%=request.protocol%><%=request.host%>/team</loc></url><url><loc><%=request.protocol%><%=request.host%>/work</loc></url><%@notes.each do |note|%><url><loc><%=request.protocol%><%=request.host%>/notes/<%=note.slug%></loc></url><%end%></urlset> Step 4: Log into your Google Webmaster and add the sitemap. In the grand scheme of things, Google is getting better and better at finding new pages you've added to your site. But every little bit helps in getting the SEO word out.