You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 02:37:12