agyanadda@gmail.com

CodeIgniter 4 Routing

CodeIgniter 4 Basics 1 min read Updated Dec 3, 2026 Topic 6 of 30

Routes connect URLs to controller methods. They live in app/Config/Routes.php.

Basic routes

  • $routes->get('about', 'Pages::about');
  • $routes->post('contact', 'Contact::send');
  • $routes->match(['get', 'post'], 'login', 'Auth::login');
  • Also put, patch, delete

Pages::about means the about() method of the Pages controller.

Placeholders

Placeholder Matches
(:num) numbers only
(:alpha) letters only
(:segment) anything except /
(:any) anything, including /

Pass matches to the method with $1, $2: $routes->get('posts/(:num)', 'Posts::show/$1');

Named routes

$routes->get('posts', 'Posts::index', ['as' => 'posts']); — build the URL with url_to('posts').

Groups

Share a prefix (and filters) for many routes: $routes->group('admin', ['filter' => 'auth'], static function ($routes) { ... });

Auto routing

Auto routing (guessing routes from controller names) is off by default for security. Define every route yourself.

Example

Example — Routes with placeholders and a group PHP
<?php
// app/Config/Routes.php
$routes->get('/', 'Home::index');
$routes->get('posts', 'Posts::index', ['as' => 'posts']);
$routes->get('posts/(:num)', 'Posts::show/$1');
$routes->get('category/(:segment)', 'Posts::category/$1');

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

// app/Controllers/Posts.php
public function show(int $id)
{
    return "Post number $id";
}

/posts/5 shows "Post number 5". /posts/abc gives 404 because (:num) only matches numbers. /admin/dashboard first runs the auth filter.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which placeholder matches numbers only?

Exercise 2 True / False

Auto routing is turned on by default in CodeIgniter 4.

Exercise 3 Fill in the Blank

Pass the first placeholder to the method using $___ in the route.

Frequently Asked Questions

(:segment) matches one URL part and stops at a slash. (:any) also matches slashes, so it can capture several parts like 2026/12/my-post. Use (:segment) unless you really need more.