Wednesday, May 1, 2013

The Importance of URL Rewriting

I am terrible about explaining things sometimes, and lately I've been working with a client on URL rewriting. I've done a lot of techno-speak but I'm not sure that I have really explained in laymans terms what URL rewriting is, and why it's important.


What is it?
When you go to your About us page on your web site right now, if you typed in the whole address into your browser, it might look something like this:
http://www.yoursite.com/index.cfm/sitepages/show/2

That URL doesn't tell us anything about the page, and it's very hard to remember.
Wouldn't it be better to have that URL be this?
http://www.yoursite.com/About-Us  

That is URL rewriting. It's the process of making your page names descriptive, instead of cryptic.

When we start rewriting those URL's, a great thing happens... you can now anticipate what a page will be.
Want to find out about services? My guess would be the URL would be:
http://www.yoursite.com/services
Want to go to the contact us page? My guess would be: 
http://www.yoursite.com/Contact-Us

Best of all, those guesses would be right! So by rewriting the URL's, the first thing we've done is make those pages easy to remember. If I'm on my smart phone and don't want to have to go to the home page of your site, to get to your contact page, I can now easily remember how to get there. With so many people using the browsers on their phones, making those pages easy to get to is going to increase your traffic.

But URL rewriting isn't just for people, it's for search engines too.
Google and other search engines give your pages a "rank."  When you do a search, the pages with the highest rankings show up first.

By making the name of the page descriptive of the content, your rank will improve, and therefore your pages will show up higher in searches.

So hopefully that is a simple explanation of what URL rewriting is, and why it's so important. If you are serious about SEO, URL rewriting is a smart thing to do.

Implementing URL rewriting in CFWheels
This is just how I do it in CFWheels. I'd really like to hear how others are accomplishing it to see if I can improve on the method.

Let's create a hypothetical table called "sitepages."
In that table, I create a field for the title of the page and a unique field for the "slug."

In the sitepages model, I add a beforeSave callback.
<!---Add this to the models init method--->
<cfset beforeSave("checktheslug")>

Then, I create the "checktheslug" function:

If the user doesn't specify a slug, then the slug takes the title of the page, replaces spaces with hyphens, and then strips out any extraneous characters like quotation marks, exclamation points, etc.

Then all I have to do is set up a route, and I'm in business:
<!---Add this to the routes --->
addRoute(name="sitepages", pattern="pages/[slug]", controller="sitepages", action="show");

No comments: