<!DOCTYPE html>
<html>
<head>
<meta http-equiv="refresh" content="3;url=https://www.example.com">
<title>頁面跳轉中...</title>
</head>
<body>
3 秒後自動跳轉至 目標頁面...
</body>
</html>
content="3;url=...":3 秒後跳轉,0 為立即跳轉。<?php
// 必須在任何輸出之前調用 (包括空白字符、BOM)
header("Location: https://www.example.com", true, 302); // 302 臨時重定向
// header("Location: https://www.example.com", true, 301); // 301 永久重定向
exit; // 關鍵:阻止後續代碼執行
output_buffering 開啟或無任何輸出前調用,否則報 Cannot modify header information。<script>window.location.href = 'https://www.example.com';</script>
// 或延遲
<script>setTimeout(() => location.href = '...', 3000);</script>
需瀏覽器支持 JS,非語義化跳轉,SEO 最差。
<?php
$url = 'https://www.example.com';
$delay = 3;
$msg = '操作成功,正在跳轉...';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="<?= $delay ?>;url=<?= htmlspecialchars($url) ?>>>
<title>跳轉中</title>
<style>body{font-family:sans-serif;text-align:center;padding-top:50px}</style>
</head>
<body>
<?= $msg ?>
<?= $delay ?> 秒後自動跳轉...
<script>
var s = <?= $delay ?>;
var el = document.querySelector('p:last-child');
var t = setInterval(() => { el.textContent = --s + ' 秒後自動跳轉...'; if (s <= 0) clearInterval(t); }, 1000);
</script>
</body>
</html>
| 場景 | 推薦方案 | 理由 |
|---|---|---|
| 表單提交後、登入/登出、API 回調 | PHP header(Location: ...) 302/303 | 標準、可攜帶 Session、SEO 友好、防重複提交 |
| 靜態頁/純 HTML 環境、維護頁面 | Meta Refresh | 無需後端支持、可顯示倒計時 |
| 永久遷移域名/URL 結構調整 | PHP header(Location: ..., 301) | 傳遞 SEO 權重、瀏覽器緩存重定向 |
| AJAX 請求需跳轉 | 返回 JSON {redirect: "url"},前端 JS 跳轉 | 不阻塞 AJAX 流程、前端可控 |
**「能用 Header 就用 Header,不能用 Header 才用 Meta,最後才考慮 JS」**。Header 重定向是 HTTP 標準語義,Meta Refresh 是降級方案,JS 跳轉僅作前端交互補充。