CI4 完全废弃 CI3 的 $route 数组路由写法,改用 app/Config/Routes.php 中 $routes->get() 等方法注册,控制器需带命名空间和 ::,占位符捕获值用 $1 表示,且路由顺序敏感,泛化规则须置于具体规则之后。

CodeIgniter 4 中 没有 $route 数组,它完全废弃了 CI3 的 application/config/routes.php 数组写法。
你在 CI3 里写的这种:
$route['about'] = 'pages/view/about'; $route['news/(:num)'] = 'news/show/$1';
在 CI4 中不会被识别、不会生效、也不会报错——框架会安静地忽略它,直接走默认路由逻辑。
CI4 对应的写法是方法调用 + 闭包
所有路由必须定义在 app/Config/Routes.php 文件中,通过 $routes 实例的方法注册,例如:
$routes->get('about', 'Pages::view');
$routes->get('news/(:num)', 'News::show/$1');注意几个关键点:
- ✅ 使用
$routes->get()、$routes->post()等动词方法,不是赋值给数组 - ✅ 控制器名要带命名空间和作用域操作符
::(如Pages::view) - ✅ 参数占位符仍可用
(:num)、(:any)、(:segment),但捕获值用$1、$2表示 - ✅ 不再支持
$route['key'] = 'controller/method'这种字符串映射语法
如果你有大量 CI3 路由需要迁移,可参考转换规则:
$route['contact'] = 'pages/contact';
→$routes->get('contact', 'Pages::contact');$route['product/(:num)'] = 'products/detail/$1';
→$routes->get('product/(:num)', 'Products::detail/$1');$route['admin/(:any)'] = 'admin/$1';
→$routes->group('admin', function($routes) { $routes->get('(:any)', 'Admin::handle/$1'); });
特别提醒:CI4 路由顺序更敏感
匹配是从上到下、命中即停。泛化规则(如 (:any))必须放在具体规则之后,否则会“吞掉”其他路径。比如:
❌ 错误顺序((:any) 在前):
$routes->get('(:any)', 'Fallback::handle'); // 所有请求都被它截住
$routes->get('api/users', 'Api::users'); // 永远不执行✅ 正确顺序:
$routes->get('api/users', 'Api::users');
$routes->get('(:any)', 'Fallback::handle');


















