10 August 2009

Using Movable Type as a Simple URL Shortener

With today’s news that tr.im is shutting down, I decided to take on a small project and write a URL shortening service within Movable Type. It’s probably not the most elegant solution, and could well break some best practices, but it works for now.

First, I created a new blog in Movable Type. With ely.fm I already have a pretty short address, so I have the blog at http://ely.fm/debigulated/ and will use ely.fm/u/ to redirect URLs from.

Next, I made a new index template that will create an .htaccess file. I set the output file to ../u/.htaccess. The content of the template I used:

<mt:Entries> Redirect 301 /u/<$mt:EntryID$> <$mt:EntryBody convert_breaks="0" encode_ampersands="1"$> </mt:Entries> 

This will use the entry ID of my posts as the short URL slug. It could be shorter if I had a way to convert it to hex or base-36 or something, but it’ll do.

Now, to debigulate a URL, I create a new entry in my new blog. The title is the name of the page I’m linking to, and its body is its URL.

In order to get the short URL I’ve made an index template that shows the short link and the long one. It also provides some semblance of a record of where the short links go if I ever shut down the service. So, edit the Entry Summary template, where it says <$mt:EntryBody$>, to something like:

<p>Short URL: http://ely.fm/<br /> Long URL: <$mt:EntryBody convert_breaks="0"$></p> 

My running list of debigulated URLs is here. (Note: it’s written in HTML 5, just for fun, and I’ve done almost no cross-browser testing. It may look like nonsense in some browsers.) The first set of links will be a running list of URLs I’ve shortened, followed by a list of links to my own blog posts, which also have self-declared shorturls. The short link for the post you’re reading right now is ely.fm/u/464.

I may also include some tracking by turning the links into Bird Feeder seeds. All of this works pretty well, but I’m sure a Movable Type plugin could do it better, or a stand-alone application one could install on a web server. Regardless, it was a good project for me to stretch my brain a little.