Search Engine Friendly URLs with Ruby on Rails

Update 2/5/07: I’ve since discovered five plugins that address this very problem with slightly different approaches (the latter two store a permalink in the table, good for mutable titles):

Obie’s recent post on search engine friendly URL’s in Ruby on Rails 1.2 and greater couldn’t have been more timely. I was about to tackle search engine friendly URL’s on my little local san francisco bay area boating classifieds site and after reading his blog post, 15 minutes later it was done. Here’s the old URL structure:

http://gearandboats.com/forums/1/topics/51

and the new (longer for humans but much better for SEO):

http://gearandboats.com/forums/1-boats/topics/51-fantasia-35-mark-ii-cruiser

The most important thing is that the URL’s are backwards compatible because everything after the ID is ignored which is key for pages that are already in the search engines!

To achieve this I combined Obie’s approach with Ricks Permalink_fu plugin (for converting text to permalinks):

script/plugin install http://svn.techno-weenie.net/projects/plugins/permalink_fu

Then in my topic.rb model object I do:

def to_param
  "#{id}-#{PermalinkFu.escape(title)}"
end

and I double checked to make sure that the views always call link_to passing the model object rather than the ID (so that the to_param method has access to the id and the title). Fortunately beast.caboo.se (which is what I based my site on) make heavy use of named routes:

<%= link_to h(topic.title), topic_path(@forum, topic) %>

After that I was pretty much done but I had some really long URL’s so I truncated the title to the first 5 words by changing

PermalinkFu.escape(title)

to

PermalinkFu.escape(title.split[0..4].join(' '))

.

This entry was posted in Ruby, Ruby on Rails, Search Engine Optimization, Software Engineering. Bookmark the permalink.

3 Responses to Search Engine Friendly URLs with Ruby on Rails

  1. SoR says:

    Don’t forget permalink_fu too! I guess thats 4 Rails URL plugins!

  2. Tore Darell says:

    Hi, just noticed your link to acts_as_sluggable is out of date.. It should be http://tore.darell.no/pages/acts_as_sluggable

    Yes, I was using acts_as_sluggable, and it changed.. That’s the downside of exposing the ID in the URL like I did 😉

  3. wom says:

    ther is another one: the UrlKey plugin
    http://railspikes.com/2007/5/15/using-urlkey

Comments are closed.