SEO Friendly URLs in Rails

Handwritten 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!

discuss on twitter

every day thousands of developers use our charts & gauges to get the job done right

JavaScript Charts JavaScript Gauges JavaScript Flight Gauges

← return to all articles