x
 
Create New Page
 View Previous Changes    ( Last updated by BenoĆ®t Marchal )

How to create a custom URL shortener

Category:.htaccess, Category:URLs, Category:Twitter

With the growing popularity of Twitter, I decided to roll out my own URL shortener (bit.ly lookalike). Turns out that it is very easy to do with Expression Engine, requiring only one template and a three lines in an .htaccess.

Step by steps

A. Create a new template. It does not really matter where you store the template, I placed mine in a global template group where I store my CSS and other site-wide templates. Mine is called shortlink but use any name you like. Below is the content of my template:

<?php
global $FNS;
{exp:weblog:entries disable="categories|category_fields|custom_fields|member_data|pagination|trackbacks" require_entry="yes"/* weird coding but we do the data retrieval in EE templates and tests in PHP... safer */
{if no_results}$FNS->redirect('http://www.declencheur.com/');{/if}
$weblog_id 
{weblog_id};
if(
$weblog_id == 1)
   
$address '{title_permalink=carnet/note}';
elseif(
$weblog_id == 3)
   
$address '{title_permalink=emission/note}';
else
   
$address 'http://www.declencheur.com';
{/exp:weblog:entries}
header
('Status: 301 Moved Permanently',false,301);
header('Location: '.$address);
exit;
?> 

Important you MUST enable PHP parsing at the output stage for this template (in the Control Panel, Templates|Preferences).

Here’s how it works.
The template is called with the entry id in the URL (i.e. URLs of the form /index.php/global/shortlink/386/), using the weblog entries tag, it retrieves the corresponding permalink and passes it to a small PHP script.

You will need to adjust two things in this template:

1. the tests on $weblog_id.
You need a test for every weblog that needs short URLs. You need to adjust the weblog id (1 and 3 in the example) to your system (you can find the weblog id through Admin|Weblog Adminstration|Weblog Management in the Control Panel).
Also you want to ajust the permalink variable to match.

2. the site domain, mine is declencheur.com, use whatever you want

B. This is optional but you probably want to register a short domain name for the redirection. My domain is 15 characters-long which is quite a long on Twitter so I registered decl.ch.
I choose to install the short domain on a separate directory so the short domain only does redirection. If this is what you want, you will need to copy index.php and path.php to the root of the short domain directory.
MSM is overkilled (and probably less convenient) since, although it’s on 2 domains, this really is (logically) one site.

C. Open the path.php you have just copied the short domain directory and edit the $template_group and $template variables to point to your shorturl template. Although optional, I recommend this step to prevent visitors from viewing your site through the short domain.

$template_group "global";
$template "shortlink"

D. Create a .htaccess in the short domain directory with the following code:

ErrorDocument 404 /index.php
RewriteEngine on
RewriteRule 
^/?c([0-9]+)/?$ /index.php/global/shortlink/$1[L] 

Here’s how it works.
The short URLs are of the form

http://decl.ch/c827

where 827 is the entry id. The rewrite rule in the .htaccess grabs the entry id and passes it to the shortlink template where the magic takes place.

That’s all!

Using short URLs in your web pages

It’s easy to use the short URLs in your templates with the {entry_id} variable. For example, I declare the shortlink in my single-entry page as follow (again, you would need to adjust the domain name):

<link rel="shortlink" type="text/html" title="{title}" href="http://decl.ch/c{entry_id}"

And here’s how offer visitors a chance to share the page on Twitter:

Share on <a href="http://twitter.com/home?status=<?php urlencode('{title}')?>+http://decl.ch/c{entry_id}+(via+@declencheur)">Twitter</a

Why bother ?

You may wonder why develop an URL shortener for my site when there are so many free services? The main reasons for me were:

- services come and go, for example I used to be happy with tr.im but they stopped operation. By building an URL shortener on a domain I own, I guarantee the service will remain available as long as my site is operational
- external services require some integration work. Not a lot of work but some work (and work that I had to redo when the service I used stopped working). Using EE is just less work. Other blogging platform (i.e. WP) also support it now
- to integrate short URLs in my page (e.g. “shortlink” auto-discovery, post to Twitter) requires making API calls which makes the site slower to load. By remaining within EE, I have a speedier service
- it automatically integrates with my server stats since requests to the short URLs show up in the server logs
- reliability some services are slow I want to control the experience for the end-user
- branding, Flickr, the New York Times, Google and Facebook use a branded domain for short URLs, why not you?

What about the c character?

You may wonder why the URLs are of the form

http://decl.ch/c827

and not the more efficient

http://decl.ch/827

(one character shorter).
The c is a marker foreseen for future extension to wiki and forum. The wiki and the forum use different IDs so I need an indicator to recognize which database table to query.
Wiki URLs would be of the

http://decl.ch/w574

format while forum URL would look like

http://decl.ch/t574

Writing those is a simple extension of the technique outlined in this article and is left as an exercice to the reader.

Category:EE1

Categories: