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

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

1
$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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$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://phpgr.blogspot.com/content-title-that-is-seo-friendly)

1 comment:

  1. Hello World, Here you can download laravel projects, codeigniter projects, php projects.

    Codeigniter Projects

    ReplyDelete