8
Mar

Generating Sitemaps With Rails

posted by gchatz 58 comments rails

Sitemaps are a cool way for describing your site’s structure to search engines.
They can be more than useful when your site’s link aren’t easily discoverable (like searches for example).

There are some examples for generating sitemaps on the fly using an .rxml template, but if you site contains a large number of links you’ll need more than that.

Identifying links to include

First, you’ll have to identify what kind of links of you’re application you want to include in the sitemap. In most cases. all links that have a search engine value should be included in the sitemap. This is more of a SEO issue and it has to do with the general layout and content of your application.

Understanding Sitemaps

Sitemaps are described here

Very shortly there are two types of sitemap formats:

  • The Sitemap files that contain a list of urls in your site
  • The Sitemap Index files that contains a list of sitemap files.

Sitemap file

The xml format of the sitemap file is like this:

<?xml version="1.0" encoding="UTF-8"?>
 <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">

   <url>
      <loc>http://www.example.com/</loc>
      <lastmod>2005-01-01</lastmod>
      <changefreq>monthly</changefreq>
      <priority>0.8</priority>
   </url>
   ...
   ...
</urlset>

Where

  • loc is the actual url
  • lastmod is the last modified date
  • changefreq defines how often this url is updated
  • priority of this url compared to other urls in your site

Changefreq will not affect how Google and other search engines update the specific url.

Sitemap Index file

The index file contains a list of the sitemap files you want to include.
The xml format of that file is as follows:

<?xml version="1.0" encoding="UTF-8"?>
   <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
   <sitemap>
      <loc>http://www.example.com/sitemap1.xml.gz</loc>
      <lastmod>2004-10-01T18:23:17+00:00</lastmod>
   </sitemap>
   <sitemap>
      <loc>http://www.example.com/sitemap2.xml.gz</loc>
      <lastmod>2005-01-01</lastmod>
   </sitemap>
   .....
   </sitemapindex>

Where loc defines the location of the sitemap file, and lastmod the last change date.

Helper Classes

We’ll need some helper classes to easily generate sitemaps and sitemap indexes.
It’s just a set of simple REXML::Document and REXML::Element derived classes.

class SitemapUrl < REXML::Element

  def initialize(loc, lastmod = nil, changefreq=nil, priority=nil)
    @loc = loc
    @lastmode = lastmod
    @changefreq = changefreq
    @priority = priority

    super("url")
    create_elements
  end

  def create_elements
    #add location
    el = self.add_element("loc")
    el.text = @loc

    if @lastmod
      el = self.add_element("lastmod")
      el.text = @lastmod
    end

    if @changefreq
      el = self.add_element("changefreq")
      el.text = @changefreq
    end

    if @priority
      el = self.add_element("priority")
      el.text = @priority
    end
  end

end

class Sitemap < REXML::Document

  attr_accessor :loc,:lastmod, :urls

  def initialize(loc=nil, lastmod=nil)
    super
    @loc = loc
    @lastmode = lastmod

    self << REXML::XMLDecl.new("1.0", "UTF-8")

    urlset = add_element("urlset")
    urlset.add_attribute("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9")

    @urls = self.root
  end

  def to_xml
    to_s
  end

  def add_url(loc, lastmod = nil, changefreq=nil, priority=nil)
    @urls << SitemapUrl.new(loc, lastmod, changefreq,priority)
  end

end

class SitemapIndex < REXML::Document
  attr_accessor :sitemaps

  def initialize
    super

    self << REXML::XMLDecl.new("1.0", "UTF-8")

    sitemapindex = add_element("sitemapindex")
    sitemapindex.add_attribute("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9")

  end

  def add_sitemap(sitemap)
    el = self.root.add_element("sitemap")
    loc = el.add_element("loc")
    loc.text = sitemap.loc
  end

  def to_xml
    to_s
  end
end

(you can download the file here )

Using Rake to generate your sitemap

We want our sitemaps to be generated periodically. We can use a rake task and a cron job that will create the xml files and compress them.
Rake tasks are extremely helpfull for that case and we can access all of our models just be setting the environment as a requirement.

namespace :myapp do 
    namespace :sitemap do

      desc "Create Products Sitemap"
       task(:products => :environment) do
          sitemap = Sitemap.new
          sitemap.add_url("http://www.myapp.gr/products/1")
          sitemap.add_url("http://www.myapp.gr/products/2")
          #add files depending on your application logic

          #delete the previous
          FileUtils.rm(File.join(RAILS_ROOT, "public/product_sitemap.xml.gz"), :force => true)

          #create the new file
          f =File.new(File.join(RAILS_ROOT, "public/product_sitemap.xml"), 'w')

          #output contents
          f.write sitemap.to_xml
          f.close

          #compress
          system("gzip #{File.join(RAILS_ROOT, 'public/product_sitemap.xml')}")

       end

       desc "Create Reviews Sitemap"
       task(:reviews => :environment) do
          sitemap = Sitemap.new
          sitemap.add_url("http://www.myapp.com/reviews/1")
          sitemap.add_url("http://www.myapp.com/reviews/2")
          #add files depending on your application logic

          #delete the previous
          FileUtils.rm(File.join(RAILS_ROOT, "public/reviews_sitemap.xml.gz"), :force => true)

          #create the new file
          f =File.new(File.join(RAILS_ROOT, "public/reviews_sitemap.xml"), 'w')

          #output contents
          f.write sitemap.to_xml
          f.close

          #compress
          system("gzip #{File.join(RAILS_ROOT, 'public/reviews_sitemap.xml')}")

       end

       desc "Create Index"
       task(:index => :environment) do
          #add each sitemap file
          products = Sitemap.new("http://www.myapp.com/products_sitemap.xml.gz")
          reviews = Sitemap.new("http://www.myapp.com/reviews_sitemap.xml.gz")
                
          index.add_sitemap(products)
          index.add_sitemap(reviews)

          #remove the previous file
          FileUtils.rm(File.join(RAILS_ROOT, "public/sitemap_index.xml.gz"), :force => true)

          #create the index file
          f =File.new(File.join(RAILS_ROOT, "public/sitemap_index.xml"), 'w')

          #write contents
          f.write index.to_xml
          f.close

          #compress
          system("gzip #{File.join(RAILS_ROOT, 'public/sitemap_index.xml')}")

       end

       desc "Create all sitemaps"
       task(:generate=> :environment) do
          #create all sitemap files
          Rake::Task["myapp:sitemap:products"].invoke
          Rake::Task["myapp:sitemap:reviews"].invoke

          #create the sitemap index file 
          Rake::Task["myapp:sitemap:index"].invoke
       end

   end
end

Create a file sitemap.rake and place it in your lib/tasks folder. (you can download it here)

Scheduling sitemap generation

Now that we have our rake task ready, we can setup a cron job that will execute this rake task periodically.
For a linux machine that would require a line in the crontab file:

#generate sitemaps daily
0 0 * * * root cd /path/to/your/application && /usr/bin/rake myapp:sitemap:generate

Don’t forget to submit your sitemap urls to search engines. There are some services that will help you submit your sitemap to more than one search engine at a time.

Comments (58)

Pin Zenbu said on May 13, 06:50 AM:

Very nice. I was doing this by wget-ing a standard page every night. Bit nasty as it majorly threw off all my statistics cause this one page took over a minute to load. This is much nicer.

I also use a small helper method
def w3c_date(date)
date.utc.strftime("%Y-%m-%dT%H:%M:%S+00:00")
end
to add lastmod values where appropiate.

This showed up a small typo in the SitemapUrl initialize method.
@lastmode = lastmod
should be
@lastmod = lastmod

Cheers.

Pin Zenbu said on May 13, 07:27 AM:

Forgot to say, I also create the sitemap files in the tmp folder and symlink them into the public folder. This way they don't get clobbered by a cap deploy as long as you relink them.

Pin David Kennedy said on Jun 16, 12:33 AM:

I have one web application that is used to run 100+ domains. We're adding content to some of these sites www.PublicWaterMan.com and www.PublicEvidenceMan.com and don't seem to be getting indexed by Google. We get hits with their 'bots' as well as Yahoo's and MSN's each night (exception_notification emails) but we don't seem to score visibility to the search engines.
Anyway, I'm just now waking up to the fact that I'm blowing it without having any sitemap.xml and wondered if I could hire you to teach me to write a routine and the cron job on my server. I know this would probably be very boring for you and I would do my best to be a 'quick study' and value your time.
My application is HUGE and has over 60 tables with each one being scoped by the website.
I am grateful for any reply.
David

Pin Jason said on Jan 21, 09:48 AM:

Thanks....complicated stuff but I am working my way through it.
Does it put the server under much load generating? I wouldnt imagine so.

Pin Phil said on Mar 12, 09:55 PM:

Brilliant! Thanks - this not only helped us with sitemap generation but also with producing xml catalogs!
thanks!

Pin akaDanPaul said on Mar 20, 07:55 PM:

thanks for the post, saved me hours! works amazing, i have a directory project i am working on for a client and we have about 900,000 urls and every single one of them is now indexed. thanks again.

Pin Carl said on Oct 29, 03:11 PM:

Thank you, so making sitemap is fun, and the results are really good!

Pin Web design Jaipur said on Oct 31, 09:09 PM:

Brilliant! Thanks - this not only helped us with sitemap generation but also with producing xml catalogs!
thanks!

Pin betclic casino said on Nov 08, 07:35 PM:

Good generating sitemaps! Thanks you for sharing!

Pin nike blazer said on Nov 10, 11:57 AM:

very good tips, thanks you very much.

Pin Nebenjob Reisevermittler said on Nov 10, 04:33 PM:

Nebenjob Reisevermittler

nice site ! :)
helped me ;)

Pin AAAAAAA said on Nov 11, 08:30 AM:

UGG Baby UGG Classic Cardy Boots UGG Classic Short Boots UGG Classic Tall Boots UGG Women's Handbags UGG Sundance Limited Edition UGG Ultra Short 5225 UGG Ultra Short Le UGG Ultra Tall 5245 Ugg Upside Tall 5163 UGG Classic Short UGG Kid's Classic Ugg Upside Tall UGG Handbags

Pin christian louboutin said on Nov 12, 04:57 AM:

yeah ,i love your site

Pin jhon said on Nov 14, 08:26 PM:

Thank you and the subject site's outstanding

it is good articale

i think you are good .

im student you.

Pin better said on Nov 14, 08:35 PM:

thank you dear

it is nice blogs.

i well thenk you.

Pin شمس الحب said on Nov 14, 10:46 PM:

Thank you and the subject site's outstanding

it is good articale

i think you are good .

im student you.

Pin منتدى said on Nov 14, 10:49 PM:

thank you dear

it is nice blogs.

i well thenk you

Pin دليل said on Nov 14, 10:51 PM:

thanks for the post, saved me hours! works amazing, i have a directory project i am working on for a client and we have about 900,000 urls and every single one of them is now indexed. thanks again

Pin شمس الحب said on Nov 14, 10:53 PM:

thank you dear

Pin Mike said on Nov 20, 08:14 AM:

Good stuff! Thanks you for sharing!

Pin aziz said on Nov 25, 04:26 PM:

thank you dear

the results are really good

Pin ali said on Nov 27, 11:59 PM:

thank u

Pin ali said on Nov 28, 12:00 AM:

thank u

4a3shab.co.cc
24dl.info
kolyoom.info

Pin ali said on Nov 28, 12:00 AM:

thank u

www.4a3shab.co.cc
24dl.info
ww.kolyoom.info

Pin ali said on Nov 28, 12:01 AM:

Pin Cryptomonadales said on Nov 28, 06:58 AM:

my blogs mostly using the second type sitemaps, anyway nicepost

Pin mania virtual said on Dec 04, 07:19 PM:

Thanks for article, I’ll just subscribe to the feed.

Pin maniavirtual said on Dec 04, 07:21 PM:

Nice point of view, keep up the good job.

Pin sb7a said on Dec 04, 07:22 PM:

thank you dear.

Pin d3aa said on Dec 04, 07:23 PM:

thank you mr.fortyoto

Pin free said on Dec 04, 07:24 PM:

good

thank you

Pin العاب said on Dec 11, 01:16 PM:

Thank you for your topic
The subject of bitter, sweet, beautiful, moon
Accept traffic
Gisele thanks from me to you
Mra thanks
To the meeting ..

Pin دردشة said on Dec 11, 01:17 PM:

Found it a great launch
I thank you very much
Appreciation and respect
Heck on the theme of Creative Commons
Kois gone by and Hloowoowo
Hkurn

Pin Best Dating Guide said on Dec 11, 04:55 PM:

Brilliant! I didn't know that was so easy.

Pin اخبار مصر said on Dec 21, 03:28 PM:

Very good and informative article,thank you!

Pin dir4host said on Dec 26, 11:53 PM:

dir4host.co.cc

nice site

Pin membuat blog said on Dec 30, 02:11 AM:

This is actually really interesting regarding your fact article here, This article is very informative.

Pin lower ab workouts said on Dec 30, 06:00 PM:

Thank you for that one! Great information on the subject.

Pin مسجات said on Jan 06, 10:24 PM:

Found it a great launch
I thank you very much
Appreciation and respect

Pin nader said on Jan 09, 10:02 AM:

So nice, many thanks.

Pin Dating Manual said on Jan 11, 01:36 AM:

The is what I call a great information! Thanks

Pin df said on Jan 12, 04:53 PM:

ملتقى هتولي

ملتقى

هتولي

htoly

Pin ملتقى هتولي said on Jan 12, 04:55 PM:

sdadasd

asdasd

Pin دردشة said on Jan 27, 04:25 PM:

Found it a great launch
I thank you very much
Appreciation and respect
Heck on the theme of Creative Commons
Kois gone by and Hloowoowo ..

Pin منتديات said on Feb 10, 01:48 AM:

Thank you for that one! Great information on the subject.

Pin شات said on Feb 10, 01:49 AM:

Thank you for that one! Great information on the subject.

Pin دردشة said on Feb 10, 07:30 PM:

This is actually really interesting regarding your fact article here, This article is very informative.

Pin mosafr said on Feb 15, 06:36 AM:

عبير - بلوتوث - توبيكات - مركز تحميل الصور جنس - فضايح - موقع عبير - توبيكات عبير المشاعر - صور فنانين زواج - دردشة - برامج - توبيكات رومانسيه مركز تحميل عبير المشاعر - تحميل الصور - تحميل الملفات - عالم المرأه توبيكات غرام - توبيكات غزل - توبيكات عيد الاضحى - اناقه وجمال توبيكات عيد الفطر - توبيكات منوعه - توبيكات رمضانيه - صحتك توبيكات ملونه - توبيكات اسلاميه - عالم الطفل - موقع عبير صور اسلاميه مقطع عبير المشاعر - مقطع رومانسيه - اكلات وحلويات - نصائح للمنزل صور فنانات - مكتبة الصور - مسجات رومانسيه مسجات رومانسية - مسجات اسلاميه خلفيات - صور لسطح المكتب - دليل الموقع دليل المصانع - sitemap مكتبة المسجات - مسجات - دليل مواقع عبير المشاعر - sitemap.php - sitemap SiteMab - الأرشيف - مسرحيات - افلام انمي - المشاعر sitemap - منتديات - منتدي عالم المرأه - شات عبير منتديات عبير المشاعر - موقع عبير - اناقه وجمال - youtube صحتك دردشة - مركز تحميل عبير المشاعر عالم الطفل دردشة عبير المشاعر اكلات وحلويات - دليل عبير المشاعر نصائح للمنزل شات عبير المشاعر Kaspersky- Anti- Virus اناشيد البوم عصومي و وليد اناشيد طيور الجنة فيديو كليب اناشيد طيور الجنة مسجات جديدة مهند ونور سمايلات + برامج نوكيا n73 برامج نوكيا n97 بلاك بيري رسائل وسائط موقع عبير عبير ثيمات صرقعه ثيمات الجوال ثيمات حب ثميات حزينه صور ثيمات ثيمات الجوال ثيمات ثيمات نوكيا ادعية اناشيد صوتيات اسلامية فضائح وجرائم نقاشات عامة سياحة وسفر صور تعليم اللغات تحميل كتب اقتصاد خواطر رومانسية قصص قصص اطفال ثقافة جنسية الاسرة والطفل سيارات ادم مسابقات انمي برامج كمبيوتر تحميل العاب توبيكات للماسنجر برامج للماسنجر صور للماسنجر صور للمسن للماسنجر مستلزمات تصميم صور للتصميم فلاش و سويتش برامج جديده مقاطع يوتيوب صور اندية لميس ويحي سنوات الضياع مسجات توبيكات للمسنجر sitemap دليل مواقع عبير المشاعر دليل الموقع الدليل مسلسلات مسلسلات رمضانيه مسلسلات كويتيه مسلسلات سعوديه افلام كومديه افلام مصريه افلام عربيه افلام كويتيه تحميل افلام عربيه تحميل افلام مصريه مركز تحميل عبير المشاعر مركز تحميل رفع الصور رفع صور مركز تحميل الملفات تحميل الصور تحميل الملفات مركز تحميل الصور توبيكات عبير المشاعر توبيكات رومانسيه توبيكات رومانسية توبيكات حزن توبيكات ملونه توبيكات اسلاميه توبيكات رمضانيه مقطع عبير المشاعر مقطع رومانسيه مقطع رومانسية مقطع فنانين وفنانات مقطع فيديو كليب مقطع نغمات عبير صور عبير المشاعر صور رومانسيه صور خلفيات صور ورود مكتبة الصور خلفيات صور لسطح المكتب مسجات رومانسيه مسجات رومانسية مسجات حزن مسجات عتاب مسجات حب مكتبة المسجات مسجات الدليل دليل دليل عبير المشاعر دليل مواقع دليل مواقع عبير المشاعر دليل الموقع دليل المصانع الأرشيف مسرحيات مسرحيات افلام انمي المشاعر عبير منتديات عبير المشاعر منتديات منتدي شات عبير المشاعر شات دردشة دردشة عبير المشاعر دليل عبير المشاعر مركز تحميل عبير المشاعر youtube - اناشيد مشاري العفاسي صور رومانسية مسجات جديدة مهند ونور سمايلات برامج نوكيا n73 رسائل وسائط ثيمات صرقعه ثيمات الجوال ثيمات حب ثميات حزينه صور ثيمات ثيمات الجوال ثيمات ثيمات نوكيا ادعية اناشيد صوتيات اسلامية فضائح وجرائم نقاشات عامة عبير سياحة وسفر صور تعليم اللغات تحميل كتب اقتصاد خواطر رومانسية قصص قصص اطفال ثقافة جنسية ريجيم مكياج حلويات ديكور الاسرة والطفل سيارات عبير رياضة مسابقات انمي برامج كمبيوتر تحميل العاب توبيكات للماسنجر برامج للماسنجر صور للماسنجر دروس فوتوشوب برامج جوال نغمات مسجات ثيمات نوكيا العاب نوكيا مقاطع فيديو للجوال مقاطع بلوتوث الأرشيف برامج ماسنجر صور للمسن للماسنجر مستلزمات تصميم صور للتصميم فلاش و سويتش برامج جديده مقاطع يوتيوب صور اندية لميس ويحي سنوات الضياع مسجات توبيكات للمسنجر sitemap دليل مواقع عبير المشاعر دليل الموقع الدليل عبير مسلسلات مسلسلات رمضانيه افلام كويتيه تحميل افلام عربيه تحميل افلام مصريه منتديات عبير عبير منتدى عبير شبكة عبير موقع عبير منتديات عبير عبير منتدى عبير شبكة عبير موقع عبير مركز تحميل عبير المشاعر توبيكات عبير المشاعر منتديات عبير المشاعر عبير المشاعر مكنبة الجوال مسجات دروس دليل مواقع عبير المشاعر عبير المشاعر عبير منتديات عبير المشاعر منتديات منتدي شات عبير المشاعر شات دردشة دردشة عبير المشاعر سيارات ادم رياضة اخبار الفنانين مسابقات انمي شات دردشة عبير __ حرير مركز تحميل حرير توبيكات حرير دليل حرير العاب حرير صوتي حرير شات حرير

Pin christian louboutin said on Feb 19, 08:45 AM:

The Cheapest Christian Louboutin Store,Shop popular Christian Louboutin shoes on salesole.

Pin منتديات said on Feb 23, 11:35 PM:

Found it a great launch
I thank you very much
Appreciation and respect
Heck on the theme of Creative Commons
Kois gone by and Hloowoowo ..

Pin Volker said on Feb 25, 06:16 AM:

Google gerade im Web und bin auf dieser schönen und informativen Homepage
gelandet. Bevor ich weiter surfe, möchte ich noch einen Gruß von der
wunderschönen Insel Sylt hinterlassen.

Pin soudiacool said on Feb 26, 06:34 PM:

سعوديه كول

soudiacool.com
شات صوتي

soudiacool.com
شات سعوديه كول

soudiacool.com
سعوديه

soudiacool.com
سعوديه كول

soudiacool.com

دردشه سعوديه

شات
سعودي

soudiacool.com
 

Pin شات كتابي said on Feb 28, 11:41 AM:

Google gerade im Web und bin auf dieser schönen und informativen Homepage
gelandet. Bevor ich weiter surfe, möchte ich noch einen Gruß von der
wunderschönen Insel Sylt hinterlassen.

Pin دلع said on Mar 01, 03:28 PM:

دلع الغربية

Drop a comment:

Pin العاب بنات said on Mar 05, 10:17 AM:

gdfgdg dfg
54545545

Pin العاب فلاش said on Mar 05, 10:17 AM:

سبلسيل يبس لبيل يبل يب

Pin سكر بنات said on Mar 05, 10:18 AM:

ghjg jghjghjgh

Pin العاب طبخ said on Mar 07, 04:04 PM:

fffffffffkjdfkjdfdfssddfdsfdfsfsfssfd

Drop a comment: