What is Routing?
Routing is a pattern matching process that captures incoming requests and decides what to do.
In CodeIgniter, you can create your own routing rules in the routes.php file located under project_folder/application/config/routes.php. By default, the routes.php file contains the following code.
<?php defined('BASEPATH') OR exit('No direct script access allowed'); $route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
The current controller set in routes.php is the welcome controller. When you try to access your site from http://localhost/yoursite
, this rule works by default and control will be passed to welcome controller.
Creating a new routing rule
In routes.php file, modify the default_controller route as:
$route['default_controller'] = 'PublicController';
Whenever you visit the URL http://localhost/yoursite
, this routing works.
Using Wildcards
In CodeIgniter, you are allowed to use the following wildcards:
- :num – Segment containing only numbers will be matched.
- :any – Segment containing only characters will be matched.
Using these wildcards allows you to have URLs with more than one segments.
Example
$route['(:any)'] = 'PublicController/index/$1';
This will be invoked when you visit url like http://localhost/yoursite/contact
Now, your routes.php
will look similar to this:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$route['default_controller'] = 'PublicController';
$route['(:any)'] = 'PublicController/index/$1';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
Here, PublicController is the controller and index is the controller method. If you try to navigate to http://localhost/yoursite an error message will be thrown as there is no controller named PublicController. So, you need to create a controller first. Next article is about creating a new controller in CodeIgniter.
Download the complete project and refer the following files:
- cisite/application/config/routes.php
- cisite/application/controllers/PublicController.php
- cisite/application/views/public/index.php