在 .htaccess 或 httpd.conf 加入:
ErrorDocument 404 /404handler.php
<?php
// === 設定區 ===
$domain = 'example.com'; // 不含 www
$docRoot = 'https://www.example.com'; // 無尾斜線
$fontFace = 'system-ui, sans-serif';
$fontSize = '1rem';
$bgColor = '#ffffff';
$textColor = '#1a1a1a';
$reportLevel = 2; // 0=關閉 1=站內 2=全部
$emailTo = 'webmaster@example.com';
// ===============
// 取得請求資訊
$uri = $_SERVER['REQUEST_URI'] ?? '/';
$referer = $_SERVER['HTTP_REFERER'] ?? '直接輸入/書籤';
$ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
// 輸出 404 頁面
http_response_code(404);
?>
<!DOCTYPE html>
<html lang="zh-Hant"><head>
<meta charset="utf-8">
<title>404 - 頁面不存在</title>
<style>
body{font-family:= $fontFace ?>;font-size:= $fontSize ?>;background:= $bgColor ?>;color:= $textColor ?>;margin:2rem auto;max-width:600px;line-height:1.6}
h1{color:#c00}
.code{font-family:monospace;background:#f5f5f5;padding:.2em .4em;border-radius:4px}
</style></head><body>
<h1>404 - 對不起,找不到您請求的頁面</h1>
<p>您請求的網址 = $docRoot . htmlspecialchars($uri) ?> 在本站不存在。</p>
<p>可能的原因:網址拼寫錯誤、頁面已移動或刪除、外部連結失效。</p>
<p><a href="= $docRoot ?>"><-- 返回首頁</a> | <a href="javascript:history.back()">返回上一頁</a></p>
<?php if ($reportLevel !== 0): ?>
<p>系統已自動記錄此錯誤,管理員將盡快處理。</p>
<?php endif; ?>
</body></html>
<?php
// === 郵件通報邏輯 ===
if ($reportLevel !== 0) {
$shouldSend = ($reportLevel === 2) ||
($reportLevel === 1 && stripos($referer, $domain) !== false);
if ($shouldSend) {
$time = date('Y-m-d H:i:s');
$subject = "【404 錯誤通報】$time - $uri";
$body = <<
$subject、$emailTo 需過濾換行符。