首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP header() 發送 301/404 狀態碼:標準寫法與兼容性處理

     編輯:PHP 相關知識

301 永久重定向

header('HTTP/1.1 301 Moved Permanently');
header('Location: https://www.example.com/new-url/');
exit(); // 必須退出,防止後續代碼執行

⚠️ 必須先發送 HTTP/1.1 301,否則默認發送 302。

404 未找到

// 標準寫法
header("HTTP/1.1 404 Not Found");
// 兼容舊版 PHP/某些 SAPI
header("Status: 404 Not Found");
// 雙重保險
header("HTTP/1.1 404 Not Found");
header("Status: 404 Not Found");

為什麼要雙重發送?

  • PHP 作為 CGI/FastCGI 運行時,部分 Web 服務器(如 Apache mod_cgi)要求 Status: 頭。
  • FastCGI (PHP-FPM) 標準支持 HTTP/1.1 狀態行。
  • 雙寫無副作用,最大兼容性。

實戰模式:統一錯誤處理函數

function sendStatus($code, $message = '', $redirectUrl = '') {
    $statusText = [
        301 => 'Moved Permanently',
        302 => 'Found',
        400 => 'Bad Request',
        401 => 'Unauthorized',
        403 => 'Forbidden',
        404 => 'Not Found',
        500 => 'Internal Server Error',
    ];
    $text = $statusText[$code] ?? $message;
    header("HTTP/1.1 $code $text");
    header("Status: $code $text");
    if ($code === 301 || $code === 302) {
        header("Location: $redirectUrl");
    }
    exit;
}

// 用法
sendStatus(404);                    // 直接 404
sendStatus(301, '', '/new-page/');  // 301 跳轉

驗證工具

  • 瀏覽器開發者工具 → Network → 查看 Response Headers。
  • 命令行:curl -I https://example.com/page。
  • 站長工具 HTTP 狀態碼查詢。

總結

發送 301/404 等狀態碼時,務必雙重發送 HTTP/1.1 與 Status: 頭,並在重定向時附帶 Location,最後 exit() 終止腳本。封裝統一函數可避免重複代碼與遺漏。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved