Creating a Sitemap Automagically for Rails App
Sitemaps help in making sure that your app is properly indexed, so it would help to automatically have them generated (and updated) so a search engine knows when a new web page is created, or an old one updated. Luckily, there’s a gem, SitemapGenerator that makes it extremely easy to do this.
All you have to do in Rails 3 is:
- add: gem ‘sitemap_generator’ to your gemfile
- run “rake sitemap:install” which creates config/sitemap.rb
- customize sitemap.rb
A simple example (where “Content” is a model name)
SitemapGenerator::Sitemap.default_host = "http://www.example.com" SitemapGenerator::Sitemap.create do add '/contact_us' Content.find_each do |content| add content_path(content), :lastmod => content.updated_at end end
4. run “rake sitemap:refresh”
5. change your robots.txt file (if you have one) to include this line (so search engines can find it easy):
6. if you’re using Heroku, like me, you’ll have to take extra steps, as in this example, to write the files to somewhere else since Heroku is read-only.
7. Also, if you’re using Heroku, you may want to use Heroku Scheduler to automatically refresh the sitemap by adding this task:
$ rake sitemap:refresh
8. Lastly, to make sure Google indexes your site better, you’ll want to enter the path to your sitemap in a Google Webmaster Tools account for your site – the same as the address in step 5, unless you are using Heroku or another read-only system (and the sitemap is stored on another domain). In this case, since Google Webmaster tools only accepts url’s from your domain (for the sitemap location), you’ll have to re-route them to the external location. To do that you can make a simple controller like this example from Bill Rowell or you can use the rack-rewite gem.