萬盛學電腦網

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

WordPress 禁止輸出錯誤資訊與敏感路徑洩露防護指南

風險場景

直接訪問主題檔案 (如 `wp-content/themes/twentytwelve/index.php`) 會觸發 `Call to undefined function get_header()` 致命錯誤,若 `display_errors=On` 會洩露絕對路徑、資料庫前綴、插件結構等敏感資訊。

三層防護策略

層級 1:PHP 配置 (根治)

; php.ini (生產環境必須)
display_errors = Off
display_startup_errors = Off
log_errors = On
error_log = /var/log/php_errors.log
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT

層級 2:Web Server 配置 (防禦深度)

# Nginx
fastcgi_param PHP_VALUE "display_errors=off";

# Apache .htaccess
php_flag display_errors off

層級 3:WordPress 代碼層 (最後防線)

在主題 `index.php`、 `page.php` 等入口檔**最頂端**添加:

<?php
// 1. 關閉錯誤顯示
ini_set('display_errors', 0);

// 2. 核心函數存在性檢查,不存在則重定向首頁
if (!function_exists('get_header')) {
    $home = home_url('/');
    header("Location: $home", true, 302);
    exit;
}

// 3. 正常載入主題
get_header();
?>

進階:自定義錯誤處理器

<?php
// wp-config.php 或 mu-plugin
function custom_error_handler(int $errno, string $errstr, string $errfile, int $errline): bool
{
    // 記錄日誌
    error_log("[$errno] $errstr in $errfile:$errline");

    // 生產環境不顯示細節
    if (defined('WP_DEBUG') && WP_DEBUG) return false; // 交給預設處理

    // 致命錯誤顯示友好頁面
    if (in_array($errno, [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])) {
        status_header(500);
        nocache_headers();
        echo '服務暫時不可用

系統維護中,請稍後再試

'; exit; } return true; } set_error_handler('custom_error_handler'); register_shutdown_function(function () { $err = error_get_last(); if ($err && in_array($err['type'], [E_ERROR, E_PARSE])) { custom_error_handler($err['type'], $err['message'], $err['file'], $err['line']); } }); ?>

安全檢查清單

  • ✅ `wp-config.php` 設定 `define('WP_DEBUG', false);`
  • ✅ 移除 `readme.html`、`license.txt`、`wp-admin/install.php`
  • ✅ 禁止目錄瀏覽:`Options -Indexes`
  • ✅ 保護 `wp-config.php`、`.htaccess`、`xmlrpc.php`
  • ✅ 定期掃描惡意代碼、更新核心/插件/主題
copyright © 萬盛學電腦網 all rights reserved