Routing in CodeIgniter

📘 CodeIgniter 👁 26 views 📅 Dec 22, 2025
⏱ Estimated reading time: 2 min

Routing defines how URLs are mapped to controllers and methods. In CodeIgniter 4, routing is powerful, flexible, and easy to configure.


1. Where Routes Are Defined

Routes are defined in:

app/Config/Routes.php

2. Basic Route Syntax

$routes->get('url', 'Controller::method');

Example

$routes->get('/', 'Home::index');

URL:

http://localhost:8080/

3. HTTP Method-Based Routing

$routes->get('users', 'UserController::index'); $routes->post('users/create', 'UserController::create'); $routes->put('users/update/(:num)', 'UserController::update/$1'); $routes->delete('users/delete/(:num)', 'UserController::delete/$1');

4. Route with Parameters

Numeric Parameter

$routes->get('product/(:num)', 'Product::view/$1');

URL:

product/10

Any String Parameter

$routes->get('blog/(:any)', 'Blog::read/$1');

URL:

blog/my-first-post

5. Default Controller & Method

Set in Routes.php:

$routes->setDefaultController('Home'); $routes->setDefaultMethod('index');

6. Route Groups

Useful for organizing routes.

$routes->group('admin', function($routes) { $routes->get('dashboard', 'Admin::dashboard'); $routes->get('users', 'Admin::users'); });

URL:

/admin/dashboard

7. Named Routes

$routes->get('login', 'Auth::login', ['as' => 'login']);

Generate URL:

route_to('login');

8. Auto Routing

Enable (Not Recommended for Production)

$routes->setAutoRoute(true);

Allows:

/controller/method

⚠️ Security Risk – better to define routes manually.


9. Redirect Routes

$routes->addRedirect('old-url', 'new-url');

10. Route Filters (Middleware)

Apply filters like authentication.

$routes->get('dashboard', 'User::dashboard', ['filter' => 'auth']);

Or group filter:

$routes->group('admin', ['filter' => 'auth'], function($routes) { $routes->get('dashboard', 'Admin::dashboard'); });

11. RESTful Resource Routing

Automatically creates CRUD routes.

$routes->resource('users');

Creates:

  • GET /users

  • POST /users

  • GET /users/{id}

  • PUT /users/{id}

  • DELETE /users/{id}


12. Example Controller

class User extends BaseController { public function profile($id) { return "User ID: $id"; } }

Summary

  • Routes map URLs → Controllers

  • Defined in app/Config/Routes.php

  • Supports parameters, groups, filters, REST APIs

  • Avoid auto-routing in production


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes