萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

ThinkPHP 404 頁面配置:空模組與空方法雙重捕獲

前言

ThinkPHP 透過「空模組」與「空方法」機制,可優雅處理不存在的控制器/Action 請求,統一導向自定義 404 頁面。本文詳細說明雙層捕獲配置步驟。

步驟 1:建立空模組控制器

路徑:App/Lib/Action/EmptyAction.class.php(TP3)或 app/controller/Empty.php(TP5/6)

<?php
namespace app\controller; // TP5/6
// class EmptyAction extends CommonAction { // TP3

class Empty extends Base { // TP5/6 繼承基礎控制器
    public function _empty() {
        // 發送標準 404 Header
        header('HTTP/1.0 404 Not Found');
        // 輸出 404 模板
        return $this->fetch('public/404'); // TP5/6
        // $this->display('Public:404'); // TP3
    }
}
?>

步驟 2:基礎控制器定義空方法(捕獲不存在的 Action)

路徑:App/Lib/Action/CommonAction.class.php(TP3)或 app/controller/Base.php(TP5/6)

<?php
namespace app\controller;

class Base extends \think\Controller {
    // 捕獲當前模組下不存在的方法
    public function _empty() {
        // 重定向到空模組的 _empty 方法
        return $this->redirect('Empty/_empty');
        // TP3: R('Empty/_empty');
    }
}
?>

步驟 3:建立 404 模板

路徑:App/Tpl/Public/404.html(TP3)或 view/public/404.html(TP5/6)

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>404 - 頁面不存在</title>
    <style>body{text-align:center;padding:100px;font-family:Microsoft YaHei;}</style>
</head>
<body>
    <h1>404</h1>
    <p>您訪問的頁面不存在或已被移除</p>
    <a href="/">返回首頁</a>
</body>
</html>

機制原理圖解

請求 URL: /NonExist/foo
    ↓
ThinkPHP 路由分發
    ↓
找不到 NonExist 控制器
    ↓
→ 實例化 Empty 控制器 (空模組)
    ↓
調用 Empty->_empty() → 顯示 404

請求 URL: /Index/NonExistAction
    ↓
找到 Index 控制器
    ↓
找不到 NonExistAction 方法
    ↓
→ 調用 Index->_empty() (空方法)
    ↓
→ 重定向到 Empty/_empty → 顯示 404

進階:記錄 404 日誌與監控

public function _empty() {
    header('HTTP/1.0 404 Not Found');
    // 記錄日誌
    \think\Log::record('404: ' . request()->url() . ' | UA: ' . request()->header('user-agent'), 'warning');
    // 可整合 Sentry、Slack 等告警
    return $this->fetch('public/404');
}

注意事項

  • TP3 使用 R() 方法調用模組操作,TP5/6 使用 redirect() 或直接 fetch()。
  • 確保 APP_DEBUG 關閉時才顯示自定義 404,開發模式下框架會顯示詳細錯誤頁。
  • Nginx/Apache 層面也應配置 error_page 404 /404.html 作為最後防線。
copyright © 萬盛學電腦網 all rights reserved