CodeIgniter router config for dynamic url (url shortener or seo friendly url)

Here’s the scenario, I want my CodeIgniter to be able to works similar to url shortener services (e.g. http://bit.ly) so I can access content by using this kind of format http://blood4lifeid.org/uac1

There’s so many tricks to this. We can use mod_rewrite on some specific pattern, or force our CI to use one Master-Controller, or rewrite CI router mechanism.

But I am going to use the easiest one, only changing CI router.php config
At first I use this on CI routes.php

$route['(:any)'] = "incidents/detail_shortened/$1";

As expected, It’s kind of working, but it makes all of my controller inaccessible, that is because any ‘/controllername/parameter/’ format will match with ‘(:any)’ and will be redirected to our ‘incidents/detail_shortened/’.

To stop controllers redirected by the CI router, I have to explicitly define all of my controllers on the routes.php first (since it’s handled in sequence)

This is the code for that:

$route['default_controller'] = "welcome";
$route['404_override'] = 'help/show404';

// define all 'normal' possible routing path
$route['callbacks'] = 'callbacks';
$route['callbacks/(:any)'] = 'callbacks/$1';

$route['faqs'] = 'faqs';
$route['faqs/(:any)'] = 'faqs/$1';

$route['help'] = 'help';
$route['help/(:any)'] = 'help/$1';

$route['welcome'] = 'welcome';

$route['welcome/(:any)'] = 'welcome/$1';

// the last resort (dynamic)
$route['(:any)'] = "incidents/detail_shortened/$1";

And now it works 🙂 all controller will he handled normally, and my shortened dynamic url will be properly
handled by my `incidents` controller.

P.S:
This applies to CodeIgniter 2.0 (i am not sure whether it works for CI < 2.0)

You can also apply this scenario for your SEO friendly dynamic URL (e.g. http://yoursite.com/content-title-that-is-seo-friendly)