萬盛學電腦網

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

PHP 實現自定義 404 錯誤頁面的多種方案

PHP 404 狀態碼與自定義錯誤頁面完整指南

正確返回 404 狀態碼對 SEO 和用戶體驗至關重要。本文涵蓋 PHP 代碼級控制、Web 服務器配置、框架集成等多層級方案。

一、PHP 代碼級 404 實現

1. 基礎 404 響應

<?php
// 必須在任何輸出之前調用
http_response_code(404); // PHP 5.4+ 推薦寫法
// 或兼容寫法
header('HTTP/1.1 404 Not Found');
header('Status: 404 Not Found'); // FastCGI 兼容

// 輸出錯誤頁面內容
echo '<h1>404 - 頁面不存在</h1>';
echo '<p>您訪問的頁面可能已移動或刪除。</p>';
exit();
?>

2. 包含自定義 404 模板文件

<?php
http_response_code(404);

// 方案 A:直接包含(變量作用域共享)
include __DIR__ . '/templates/404.php';
exit();

// 方案 B:捕獲輸出(隔離變量作用域)
ob_start();
include __DIR__ . '/templates/404.php';
$content = ob_get_clean();
echo $content;
exit();
?>

3. 404 模板文件範例 (templates/404.php)

<!DOCTYPE html>
<html lang="zh-Hant">
<head>
    <meta charset="UTF-8">
    <title>404 - 頁面未找到</title>
    <style>
        body {font-family: system-ui; text-align: center; padding: 50px; color: #333;}
        h1 {font-size: 72px; margin: 0; color: #e74c3c;}
        a {color: #3498db; text-decoration: none;}
        a:hover {text-decoration: underline;}
    </style>
</head>
<body>
    <h1>404</h1>
    <p>抱歉,您訪問的頁面不存在或已被移除。</p>
    <p><a href="/">返回首頁</a> | <a href="/sitemap">查看網站地圖</a></p>
    <p><small>請求路徑:<?= htmlspecialchars($_SERVER['REQUEST_URI']) ?></small></p>
</body>
</html>

二、Web 服務器級配置(推薦,性能更好)

1. Apache (.htaccess)

# .htaccess
ErrorDocument 404 /404.html
# 或動態處理
ErrorDocument 404 /error.php?code=404

2. Apache (httpd.conf / vhost.conf)

<VirtualHost *:80>
    DocumentRoot /var/www/html
    ErrorDocument 404 /404.html
    # ErrorDocument 404 "/cgi-bin/404_handler.pl"
</VirtualHost>

3. Nginx 配置

server {
    listen 80;
    server_name example.com;
    root /var/www/html;
    
    # 靜態 404 頁面
    error_page 404 /404.html;
    location = /404.html {
        internal; # 防止直接訪問
    }
    
    # 或動態處理
    # error_page 404 /error.php?code=404;
    
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }
    
    location ~ \.php$ {
        fastcgi_pass unix:/run/php/php-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
        # 關鍵:將 PHP 返回的 404 傳遞給 nginx
        fastcgi_intercept_errors on;
    }
}

三、框架集成最佳實踐

Laravel

<?php
// app/Exceptions/Handler.php
public function render($request, Throwable $e) {
    if ($e instanceof NotFoundHttpException) {
        if ($request->expectsJson()) {
            return response()->json(['message' => 'Not Found'], 404);
        }
        return response()->view('errors.404', [], 404);
    }
    return parent::render($request, $e);
}

// resources/views/errors/404.blade.php
// 自定義模板
?>

ThinkPHP 6/8

<?php
// config/exception.php
return [
    'http' => [
        404 => \app\exception\HttpExceptionHandler::class,
    ],
];

// app/exception/HttpExceptionHandler.php
namespace app\exception;
use think\exception\Handle;
use think\Response;

class HttpExceptionHandler extends Handle {
    public function render(\Throwable $e): Response {
        if ($e->getCode() == 404) {
            return Response::create('errors/404', 'view')->code(404);
        }
        return parent::render($e);
    }
}
?>

Symfony

<?php
// config/packages/twig.yaml
twig:
    exception_controller: 'App\Controller\ExceptionController::show'

// src/Controller/ExceptionController.php
public function show(Request $request, FlattenException $exception, DebugLoggerInterface $logger = null) {
    $statusCode = $exception->getStatusCode();
    if ($statusCode === 404) {
        return $this->render('error/404.html.twig', [], new Response('', 404));
    }
    // ...
}
?>

四、常見錯誤與避坑指南

錯誤做法後果正確做法
只輸出內容,不發送 404 狀態碼搜索引擎以為頁面正常(軟 404),影響 SEO必須發送 http_response_code(404)
使用 header('Location: /404.html')返回 302 重定向,搜索引擎不識別為 404直接輸出內容或服務器級配置
在輸出內容後發送 header"Cannot modify header information" 警告,header 無效確保 header 在任何輸出前調用
FastCGI 下只用 header('HTTP/1.1 404')部分環境無效雙重發送:header('Status: 404 Not Found')
404 頁面返回 200 OK軟 404,嚴重 SEO 懲罰檢查網絡面板確認狀態碼

五、進階:動態 404 智能推薦

<?php
http_response_code(404);

$requestUri = $_SERVER['REQUEST_URI'];
$suggestions = [];

// 簡單相似度匹配(生產環境建議用搜索引擎或 Levenshtein 距離)
$pages = ['/about', '/contact', '/products', '/blog', '/services'];
foreach ($pages as $page) {
    similar_text($requestUri, $page, $percent);
    if ($percent > 40) {
        $suggestions[] = ['url' => $page, 'percent' => round($percent)];
    }
}

usort($suggestions, fn($a, $b) => $b['percent'] - $a['percent']);
$suggestions = array_slice($suggestions, 0, 3);
?>

<!DOCTYPE html>
<html>
<head><title>404 - 頁面未找到</title></head>
<body>
    <h1>404 - 頁面不存在</h1>
    <?php if ($suggestions): ?>
        <p>您是否在找:</p>
        <ul>
            <?php foreach ($suggestions as $s): ?>
                <li><a href="<?= $s['url'] ?>"><?= $s['url'] ?></a> (<?= $s['percent'] ?>% 相似)</li>
            <?php endforeach; ?>
        </ul>
    <?php endif; ?>
    <p><a href="/">返回首頁</a></p>
</body>
</html>
copyright © 萬盛學電腦網 all rights reserved