Fri, 07 Dec 07

More on those friendly URLs

So, not being able to sleep does have some benefits. I managed to get started on my latest little pet project.

I had been using apache and mod_rewrite to redirect “chrisroos.co.uk/amazonwishlist” to my actual wishlist. I had something like this in my apache config.

<VirtualHost *:80>
  ServerAdmin webmaster@seagul.co.uk
  ServerName chrisroos.co.uk
  ServerAlias www.chrisroos.co.uk
  RewriteEngine On
  # <anything>.chrisroos.co.uk -> chrisroos.co.uk
  RewriteCond %{HTTP_HOST} !^chrisroos.co.uk$ [NC]
  RewriteRule ^/(.*)$ http://chrisroos.co.uk/$1 [R=301,L] 
  # Amazon Wishlist
  RewriteRule ^/amazonwishlist http://www.amazon.co.uk/gp/registry/IO9HVNCPEWGD [R]
</VirtualHost>

I’ve replaced that with a much simpler apache config that proxies requests to my new mongrel redirection handler thing (source – hey, even that URL passes through my redirection service).

<VirtualHost *:80>
  ServerName www.chrisroos.co.uk
  ServerAlias chrisroos.co.uk
  RewriteEngine On
  RewriteRule (.*) http://localhost:4010$1 [P]
</VirtualHost>

Feel free to go run this on your own server if you’re so inclined. At the moment you’ll have to generate the redirection rules by hand. In irb, you can do something like:

# require 'yaml'
# # For www.example.com
# rules = { 'www.example.com' => 'example.com' }
# File.open('PATH_TO_RULES_FOLDER' + '/www.example.com', 'w') { |file| file.puts(rules.to_yaml) }
# # For example.com
# rules = { '/google' => 'www.google.com' }
# File.open('PATH_TO_RULES_FOLDER' + '/example.com', 'w') { |file| file.puts(rules.to_yaml) }

Start the redirection server.

$ REDIRECTION_PORT=XXXX ruby mongrel-redir.rb &
$# Leaving out REDIRECTION_PORT will mean that the server starts on port 4000
$# Leaving out the final ampersand (&) will mean that server runs in the foreground

Visit www.example.com/google1 and watch2 as you’re redirected first to example.com/google and then onto www.google.com. Cool huh.

Lots to do – notably a user interface for managing rules but it’s not a bad start.

Oh, and this is specifically so that you can redirect from your own domain. If you don’t care about the domain then you could try tinyurl or, for human friendly URLs, decent url.

1 Assuming, of course, that www.example.com and example.com both point to the server that this redirection server is running on.

2 You probably won’t be able to watch as it’ll redirect too quickly in the browser – your best bet is to use curl or the Live HTTP Headers firefox extension so see what’s actually going on.