Seventh Octave

We're Starters. We write about culture, design and the business of software.

We believe software should be beautiful and inspired. Follow us as we build @TechOctave.

SEO Friendly URLs in Rails TVD Oct 01

2 comments Latest by TVD

Yesterday, a client asked about the potential for SEO friendly URLs for his web project. Apparently, every time he'd ask a consultant about SEO friendly URLs he always got the spiel about how difficult it is.

I always laugh when I hear these things. You see, with the simplicity and power of Rails, SEO friendly URLs are not only possible, they are expected!

Sweet Google Slugs

Here's a quick run down of the process. Take for example a blog post called SEO Friendly URLs in Rails.


This is an example of how to setup RESTful routes in Rails. I'll elaborate on Rails and RESTful architecture another time.

map.resources :posts

UPDATE: The above route was written for Rails 2.3.8. Here is the updated Route for Rails 3.0:

resources :posts


In your Post domain model, override the to_param method. Here, you can specify the unique id format for each instance of a Post object:

def to_param
  "#{id}-#{title.downcase.gsub(/[^a-zA-Z0-9]+/, '-').gsub(/-{2,}/, '-').gsub(/^-|-$/, '')}"

Here, to_param is composed of three regular expressions that are worth discussing in details:

  1. Removes all non alphanumeric characters from the string.
  2. No more than one of the separator in a row.
  3. Remove leading/trailing separator.


Creating a hyperlink from the Post model will create a reference of /posts/26-seo-friendly-urls-in-rails Voila! A nice Google slug for your friendly neighborhood Google Bot spider:

<%= link_to @post.title, @post %>


When you go to show the specific post, the actual :id is 26-seo-friendly-urls-in-rails.

def show
  @post = Post.find(params[:id])

As you already know, your :id needs to be an integer value. But, don't worry, Rails is smart enough to call Ruby's to_i to convert your :id to an integer.

With Rails you crack open a big bottle of Awesome and BAMM! You've got SEO friendly URLs. That's good news! Take it from me, you've got better things to worry about, like figuring out how to host your Rails application.

Either way, you run into trouble, you drop me a line!

If you enjoyed this post, subscribe for updates (it's free).

Email Address:

2 comments so far

Matt Darby 02 Oct 10

I prefer #parameterize (my little addition the the Rails Core): def to_param "#{id}-#{title.parameterize}" end It takes care of all those gsubs for you.

TVD 02 Oct 10

Eliminates the potential for duplication of code. Less code to write and it's clean. When applicable, I think I really like this parameterize.

Comments are closed