CodeIgniter Url Routing

By default, URLs in CodeIgniter are designed to be search-engine and human friendly.

Setting your own routing rules

Routing rules are defined in routes.php file in your application/config/ file. In it you'll see an $route array, it permits you to specify your own routing criteria. Routes can either be specified using Wildcards or Regular Expressions.

Wildcards

There are two types of wildcards:

  • :num will match a segment containing only numbers.
  • :any will match a segment containing any character (except for '/', which is the segment delimiter).

Examples:

Below the few routing examples:

$route['about'] = 'page';

A URL containing the word "about" in the first segment will be remapped to the "page" class.

$config['blog/saarthak'] = 'blog/user/25';

A URL containing the segments blog/saarthak will be remapped to the "blog" class and the "user" method. The ID will be set to "25".

$route['product/(:num)'] = 'catalog/productDetail/$1';

A URL with "product" as the first segment, and a number in the second will be remapped to the "catalog" class and the "productDetail" method passing in the match as a variable to the method.

Regular Expressions

We can use regular expressions to define your routing rules. Any valid regular expression is allowed, as are back-references.

$route['products/([a-z]+)/(\d+)'] = '$1/id_$2';

In the above example, a URI similar to products/shirts/123 would instead call the "shirts" controller class and the "id_123" method.

Reserved Routes

There are three reserved routes:

$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = 'FALSE';