Yii2子目录下控制器访问报404的路由配置问题如何解决
问题根因
Yii2路由匹配时,同名控制器优先级高于同名单词的控制器子目录:你根目录下存在ReportController,访问路径report/report1时,框架会优先匹配根目录的ReportController,将第二段report1解析为动作ID,查找actionReport1()方法,不存在就返回404。
可行解决方案
方案1:配置控制器映射(适配固定数量的子控制器,无需修改其他逻辑)
在应用配置文件config/web.php的components块中添加controllerMap配置:
return [ // 其他配置项 'components' => [ // 其他组件配置 'controllerMap' => [ 'report/report1' => 'app\controllers\report\Report1Controller', 'report/report2' => 'app\controllers\report\Report2Controller', 'report/report3' => 'app\controllers\report\Report3Controller', ], ], ];
配置完成后直接访问https://myreporting.test/report/report1即可正常路由到对应控制器的actionIndex()。
方案2:配置URL规则(适配后续新增的同格式子控制器,无需反复改配置)
在config/web.php的urlManager组件中新增匹配规则:
return [ // 其他配置项 'components' => [ // 其他组件配置 'urlManager' => [ 'enablePrettyUrl' => true, 'showScriptName' => false, 'rules' => [ // 匹配带动作的路径 'report/<controller:report\d+>/<action:\w+>' => 'report/<controller>/<action>', // 匹配省略index动作的路径 'report/<controller:report\d+>' => 'report/<controller>/index', ], ], ], ];
该规则会优先匹配report/开头的子控制器路径,后续新增Report4Controller等同类控制器时无需修改配置即可自动适配。
验证方法
可以临时将根目录的ReportController.php移出项目目录,若此时访问report/report1返回正常,即可完全确认是同名优先级导致的路由冲突。
内容的提问来源于stack exchange,提问作者Andreas Hinderberger
相关产品推荐
相关产品推荐

