使用Yii2开发YouTube克隆项目时自定义控制器出现404错误
Yii2后台自定义控制器404错误排查方案
1. 核对访问URL
后台模块的正确访问格式分两种情况:
- 未启用URL美化:
域名/backend/index.php?r=hello/index - 已启用URL美化:
域名/backend/hello(index是默认动作可省略)
注意URL中的控制器名是小写短横线格式,HelloController对应hello,不要写错大小写。
2. 检查路由配置
打开backend/config/main.php,确认urlManager配置无冲突:
'components' => [ 'urlManager' => [ 'enablePrettyUrl' => true, 'showScriptName' => false, 'rules' => [ // 避免存在覆盖hello路由的自定义规则 ], ], ],
3. 验证控制器文件规范
- 文件名必须是
HelloController.php(首字母大写,Linux服务器对大小写敏感) - 确认文件放在
backend/controllers/目录下,路径无误
4. 核对控制器代码
确保命名空间、类名继承完全正确(你的代码这部分没问题,可再核对):
<?php namespace backend\controllers; use yii\web\Controller; class HelloController extends Controller { public function actionIndex() { return $this->render('index'); } }
5. 确认视图文件规范
- 视图目录必须是
backend/views/hello/(小写hello对应控制器名) - 视图文件名必须是
index.php,你的代码内容无误:
<?php echo "Hello World!"; ?>
6. 服务器重写规则检查(启用URL美化时)
- Apache服务器:
backend/web/目录需有.htaccess文件:
RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . index.php
- Nginx服务器:配置文件需添加重写规则:
location /backend { try_files $uri $uri/ /backend/index.php?$args; }
7. 清除Yii缓存
删除backend/runtime/cache/目录下的所有文件,或开启调试模式(入口文件添加defined('YII_DEBUG') or define('YII_DEBUG', true);)避免缓存干扰。
内容的提问来源于stack exchange,提问作者SusgUY446
相关产品推荐
相关产品推荐

