How to create SEO friendly URL’s on your rails web application

When you are creating something for the web, you have to keep in mind that your website must be as easy to find as possible.

SEO, or Search Engine Optimization (http://en.wikipedia.org/wiki/Search_engine_optimization) should always be in your mind when designing and creating your website.

Lets imagine a blog. By default the route to each post would be something like:
http://domain.com/post/post_id
which works just fine.
But this is not SEO friendly, as the search engine crawlers won’t link the URL to the content.

A more friendly URL would include the post title, so the crawler links it directly to the content. Although this raises a problem: what about special chars?

Well, this little workaround does the trick. The idea is for a post with a title like “This is the post title :)” to create a url like this “this-is-the-post-title”.
Downcasing and replacing all the non letters and non numeric characters.

Let’s see how:

1 – Create a field called url on your class/table

2 – Create a helper class called SeoHelper in a file called seo_helper.rb, with the following content

class SeoHelper
  
  def self.to_url (sentence)
     sentence.downcase.gsub(/[^a-z0-9]+/i, '-')
  end
end

3 – Before saving your object, populate the url with method provided by the helper class

def Save
    post = Post.new(params[:post])
    post.url = SeoHelper.to_url(post.title)
    post.save
    ...
end

4 – On the blog page, look for the url field instead of the post id.

2 thoughts on “How to create SEO friendly URL’s on your rails web application”

  1. Hello there! Do you know if they make any plugins to assist with
    Search Engine Optimization? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing
    very good gains. If you know of any please
    share. Cheers!

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA Image

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>