雖然 window.location.href 是主流跳轉方式,但在以下場景需純服務端/HTML 實現:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="refresh" content="3;url=https://www.example.com">
<title>頁面跳轉中...</title>
</head>
<body>
<p>3 秒後自動跳轉至 目標頁面...</p>
</body>
</html>
content 格式:延遲秒數;url=目標網址。0 表示立即跳轉。
<?php
// 立即跳轉
header("Location: https://www.example.com");
exit(); // 必須終止腳本執行
// 延遲跳轉(需配合 HTML 輸出)
header("Refresh: 3; url=https://www.example.com");
echo "3 秒後跳轉...";
?>
注意:header() 必須在任何輸出(含空白字符、BOM)之前調用,否則會觸發 Headers already sent 警告。
<?php
// 永久移動(SEO 傳遞權重)
header("HTTP/1.1 301 Moved Permanently");
header("Location: https://www.new-domain.com");
// 暫時重定向(預設行為)
header("HTTP/1.1 302 Found");
header("Location: https://www.example.com/temp");
exit();
?>
| 方案 | 適用場景 | SEO 友好 | 延遲支援 |
|---|---|---|---|
| Meta Refresh | 靜態頁、禁用 JS 環境 | 一般(Google 支援,但非最佳) | 原生支援 |
| PHP Header Location | 後端邏輯控制、表單提交後 | 優(301/302 可控) | 需 Refresh 頭 |
| HTTP 301/302 | 域名遷移、REST API 規範 | 最佳 | 不支援(立即執行) |
header("Location: ...") + exit()。header("Refresh: ...") 或 Meta 標籤。ob_start())可緩解頭部已發送問題。