URI Routing
Relevant source files
The following files were used as context for generating this wiki page:URI Routing in CodeIgniter 4 is the mechanism that associates a URI (Uniform Resource Identifier) with a specific controller method, a closure, or a redirect. It allows for the creation of clean, human-readable URLs, decoupling the application's URL structure from its file system layout. This system provides flexibility for designing SEO-friendly URLs and organizing application logic effectively.
The routing engine processes incoming requests, matches the URI against a set of user-defined rules, and dispatches the request to the appropriate handler. This process is central to how the framework handles every HTTP request, making it a fundamental concept for application development. Routes are primarily defined in the app/Config/Routes.php file.
Sources: source/incoming/routing.rst:3-12
How Routing Works
When an HTTP request is made to the application, the web server directs it to the main index.php file. The CodeIgniter framework then bootstraps and initializes the routing service. The Router class compares the request's URI string against the patterns defined in the route configuration file. The first matching rule is used, and the request is then handed off to the corresponding controller and method, or an anonymous function (Closure). If no match is found, a "404 - Page Not Found" error is triggered.
Sources: source/installation/running.rst:18-25, source/incoming/routing.rst:14-20
The following diagram illustrates the basic request routing flow:
This diagram shows how an incoming HTTP request is processed by the framework, matched against defined routes, and finally handled by a controller or closure.
Sources: source/incoming/routing.rst:14-20, 483-487
Defining Routes
Sources: source/incoming/routing.rst:22-25
Routes are configured in app/Config/Routes.php. The system creates an instance of the RouteCollection class, accessible as $routes, which is used to define all routing rules.
HTTP Verb Routes
The most common way to define a route is by using methods that correspond to HTTP verbs. These methods take the URI pattern to match as the first parameter and the handler (controller/method string or Closure) as the second.
| Method | Description |
|---|---|
$routes->get() | Matches only GET requests. |
$routes->post() | Matches only POST requests. |
$routes->put() | Matches only PUT requests. |
$routes->head() | Matches only HEAD requests. |
$routes->options() | Matches only OPTIONS requests. |
$routes->patch() | Matches only PATCH requests. |
$routes->delete() | Matches only DELETE requests. |
$routes->match() | Matches multiple specified verbs. The first argument is an array of verbs. |
$routes->any() | Matches all HTTP verbs. Not recommended for security reasons. |
Sources: source/incoming/routing.rst:27-44
A basic route definition looks like this:
// In app/Config/Routes.php
// A GET route to show a list of products
$routes->get('products', 'Product::index');
// A POST route to save a new product
$routes->post('products', 'Product::create');
Sources: source/incoming/routing.rst:29-31
Placeholders and Regular Expressions
Routes can use placeholders to match dynamic segments in a URI. CodeIgniter provides several built-in placeholders.
| Placeholder | Description | Example |
|---|---|---|
(:any) | Matches any character from that point on. | blog/(:any) |
(:segment) | Matches any single URI segment. | users/(:segment) |
(:num) | Matches any integer. | product/(:num) |
(:alpha) | Matches any alphabetic character. | category/(:alpha) |
(:alphanum) | Matches any alphanumeric character. | user/(:alphanum) |
(:hash) | Same as (:segment), used for IDs. | item/(:hash) |
Sources: source/incoming/routing.rst:104-121
You can also use custom regular expressions for more complex matching. The matched part of the expression is passed as a parameter to the handler method.
// Matches a URI like /products/shoes/123
$routes->get('products/(:segment)/(:num)', 'Product::show/$1/$2');
In the example above, $1 and $2 are back-references to the matched segments from the URI.
Sources: source/incoming/routing.rst:95-98
Advanced Routing
Closures
Instead of routing to a controller, you can map a route directly to a Closure (an anonymous function). This is useful for small, simple tasks that don't warrant a full controller method.
$routes->get('hello', static function () {
return 'Hello World!';
});
Sources: source/incoming/routing.rst:162-167
Named Routes
You can assign a name to a route, which makes it easy to reference in other parts of your application, such as when generating URLs in views or controllers. This decouples your code from specific URI structures.
// Define a named route
$routes->get('users/(:num)', 'User::show/$1', ['as' => 'user_profile']);
// Later, generate a URL for it
$url = route_to('user_profile', 15); // Generates: http://example.com/users/15
Sources: source/incoming/routing.rst:200-213
Grouping Routes
The group() method allows you to apply common options, like a namespace or a filter, to a set of routes. This helps to keep your route definitions DRY (Don't Repeat Yourself).
This diagram shows how a group can apply a common namespace and filter to multiple routes.
$routes->group('admin', ['namespace' => 'App\Controllers\Admin', 'filter' => 'login'], static function ($routes) {
$routes->get('users', 'Users::index');
$routes->get('products', 'Products::list');
});
This code block applies the App\Controllers\Admin namespace and the login filter to all routes defined within the group.
Sources: source/incoming/routing.rst:223-242, source/incoming/filters.rst:111-115
Route Options
Several options can be applied to routes to modify their behavior.
| Option | Description |
|---|---|
as | Specifies a name for the route (Named Routes). |
filter | Specifies a filter to run before or after the controller. |
namespace | Overrides the default controller namespace for a route or group. |
hostname | Restricts the route to a specific hostname or subdomain. |
subdomain | A shortcut to restrict a route to a subdomain. |
offset | Changes which URI segment is used for parameter matching. |
redirect | Specifies that this is a redirect route. The second parameter is the new URI. |
Sources: source/incoming/routing.rst:277-386
Auto Routing
CodeIgniter offers two modes of "auto-routing," which automatically map URIs to controllers and methods without explicit route definitions. This feature can be enabled or disabled in app/Config/Feature.php via the autoRoutes setting.
Auto Routing (Improved)
This is the default and recommended auto-routing method. It is more secure than the legacy version. It follows a strict directory/controller/method/param convention.
The logic for improved auto-routing is as follows:
Auto Routing (Legacy)
The legacy version is more flexible but less secure, as it may allow unintended controller methods to be called. It can be enabled by setting $autoRoutesImproved to false in app/Config/Routing.php. Its use is discouraged.
Sources: source/incoming/routing.rst:554-560
Command-Line (CLI) Routing
Routing is not limited to HTTP requests. It is also used to direct commands entered on the command line to the correct handler. CLI routes are also defined in app/Config/Routes.php.
// A CLI-only route
$routes->cli('migrate', 'App\Commands\Migrate::run');
This route maps the command php spark migrate to the run() method of the App\Commands\Migrate class.
Sources: source/incoming/routing.rst:462-471, source/cli/cli_commands.rst:18-22
Global Route Configuration
Several global options in app/Config/Routes.php control the overall behavior of the routing system.
| Property | Description | Default Value |
|---|---|---|
$defaultNamespace | The controller namespace used when no namespace is specified in a route. | App\Controllers |
$defaultController | The controller to load when the URI contains no information. | Home |
$defaultMethod | The method to call on the default controller. | index |
$translateURIDashes | If true, dashes in the URI are converted to underscores in the method name. | false |
$override404 | Allows specifying a controller/method or Closure to handle 404 errors instead of the default error page. | null |
$autoRoute | Deprecated. Enables or disables auto-routing globally. Use Feature Tests instead. | false |
Sources: source/incoming/routing.rst:423-459, source/general/configuration.rst:114-118
Summary
URI Routing is a powerful and essential feature of CodeIgniter 4. It provides a flexible API for mapping URIs to application logic, supporting everything from simple GET requests to complex, grouped, and filtered routes. By defining explicit routes, developers can create secure, predictable, and maintainable applications with clean URLs. While auto-routing is available for rapid development, defining routes manually is the recommended practice for production applications to ensure security and clarity.