SyntaxHighlighter

Thursday, July 16, 2009

A dot at the end of the URL

If you have urls that tend to get emailed or posted on social networks, you may sometimes get links to your site where the dot - the period at the end of the sentence - is added to the <a href=""> tag or a white space is added in the middle.

In Ruby on Rails, the . is a very important separator - it's used by Routes to determine the format of a request (html, xml, etc). The space is also unexpected, but will not be trimmed naturally if it is in the middle of the url.

If you want to reduce those "The resource cannot be found." errors, you can handle it in a couple ways:

You can modify your .htaccess file. A fine solution, but if you don't have access to the server, or just like to do it in Rails, here's a way to modify routes.

Say you had an object called 'item' and you wanted to have it show up when someone entered the url /73md8 or something - this is common with tinyurl-like ulrs - we want to keep the url short and the 'pid' is all we need to determine the page to show.

In Routes.rb, you might have something like this:

map.item '/:pid', :controller => 'items', :action => 'show'

But, this would not work with the spaces or period at the end. Try this and you'll have no problems with urls that have spaces or periods.

map.item '/:pid', :controller => 'items', :action => 'show', :requirements => { :pid => /[a-zA-Z0-9\.%]+/ }

The '%' is needed to catch %20 (the space character) and other escaped characters.

At somepoint, you just can't fix a broken link, but this is more flexible in the most common cases.

No comments:

Post a Comment