ThinkPHP 3.x 透過 EmptyController 與空操作 _empty() 機制,可優雅處理找不到控制器或方法的情況,導向自定義 404 頁面。
路徑:Home/Controller/EmptyController.class.php
<?php
namespace Home\Controller;
use Think\Controller;
class EmptyController extends Controller {
// 空操作:找不到方法時觸發
public function _empty() {
header("HTTP/1.0 404 Not Found");
$this->display("Public:404"); // 顯示 Public/404.html
}
// 空控制器預設動作
public function index() {
header("HTTP/1.0 404 Not Found");
$this->display("Public:404");
}
}
?>
路徑:Home/Controller/PublicController.class.php
<?php
namespace Home\Controller;
use Think\Controller;
class PublicController extends Controller {
public function _empty() {
// 重導向至靜態 404 頁面(需對應實際路徑)
header("Location:/404.html");
exit;
}
}
?>
<?php
namespace Home\Controller;
// use Think\Controller; // 註釋掉原本繼承
class IndexController extends PublicController {
public function index() {
// 正常業務邏輯
}
}
?>
header("HTTP/1.0 404 Not Found") 告知瀏覽器/搜尋引擎此為 404 頁面$this->display("Public:404") 對應 Home/View/Public/404.htmlheader("Location:/404.html") 需確保靜態頁面存在於網站根目錄PublicController → Think\Controller在 Common/Conf/config.php 設定:
'ERROR_PAGE' => '/404.html', // 全域錯誤頁面
'SHOW_ERROR_MSG' => false, // 生產環境關閉詳細錯誤
app/ExceptionHandle.php 或配置 exception_tmpl