Main Content

Carrying a long URL around - looking for memorable shorts

Archive - Originally posted on "The Horse's Mouth" - 2010-05-17 16:32:48 - Graham Ellis

Are you sometime envious of nice, short URLs - you want to pass on a really short URL to someone, but the structure of your site is such that the resource in question has some long string associated with it - it has to carry a lot af "context" around with it ...

There are services such as tinyurl available - or if you want more control, you can write your own. You could, for example, map
  http://www.wellho.net/short/3
onto
  http://www.wellho.net/resources/globalindex.html

How?

1. Use Apache mod_rewrite to map all URLs in the short directory to a PHP script:
  RewriteRule ^(.*)$ index.html?shortform=&%{QUERY_STRING} [L]

2. Use that PHP script to perform the mapping - in this example, I have my mappings in a file but there's no reason I shouldn't use a database:

$forward = file("forward.txt");
if (preg_match('/^(\d+)/',$_REQUEST[shortform],$gotten)) {
  if ($gotten[1] >= 0 and $gotten[1] < count($forward)) {
    $fn = trim($forward[$gotten[1]]);
    header("Location: http://www.wellho.net".$fn);
    exit();
    }
  }


You'll note that my use of a location header causes the browser to direct.

3. Highly Recommended. Tell your robots.txt file that you do not want search engines to index the short page names; if it was index, you would be diluting your search engine placement.
  Disallow: /short/