header('HTTP/1.1 301 Moved Permanently');
header('Location: https://www.example.com/new-url/');
exit(); // 必須退出,防止後續代碼執行
⚠️ 必須先發送 HTTP/1.1 301,否則默認發送 302。
// 標準寫法
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");
Status: 頭。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 跳轉
curl -I https://example.com/page。發送 301/404 等狀態碼時,務必雙重發送 HTTP/1.1 與 Status: 頭,並在重定向時附帶 Location,最後 exit() 終止腳本。封裝統一函數可避免重複代碼與遺漏。