方式一:header() HTTP 重導向(伺服器端)
$url = 'https://www.example.com/';
header("Location: $url");
exit; // 必須 exit 防止後續代碼執行
- 狀態碼預設 302(暫時重導向)
- SEO 傳遞權重、瀏覽器歷史記錄可回退
301 永久重導向(網站改版、域名遷移)
header("HTTP/1.1 301 Moved Permanently");
header("Location: $url");
exit;
方式二:HTML Meta Refresh(客戶端)
<meta http-equiv="refresh" content="5;url=https://www.example.com/">
- 5 秒後跳轉,可顯示倒數提示頁面
- 不利 SEO、無法傳遞 Referer、可被瀏覽器攔截
方式三:JavaScript 跳轉
直接跳轉(無 Referer)
<script>window.location.href = 'https://www.example.com/';</script>
模擬點擊連結(保留 Referer)
<script>
var a = document.createElement('a');
a.href = 'https://www.example.com/';
document.body.appendChild(a);
a.click();
</script>
PHP 統一跳轉工具函式
function redirect($url, $statusCode = 302, $delay = 0, $message = '') {
if ($delay > 0) {
// 延遲跳轉:輸出 HTML 頁面含 Meta/JS
echo "";
if ($message) echo "$message";
exit;
}
// 立即跳轉
if (php_sapi_name() !== 'cli') {
header("HTTP/1.1 $statusCode");
header("Location: $url");
}
exit;
}
// 使用
redirect('https://www.example.com/', 301); // 301 永久
redirect('https://www.example.com/', 302, 3, '3秒後跳轉...'); // 延遲 3 秒
進階:PRG 模式(Post-Redirect-Get)
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// 處理表單...
$_SESSION['flash'] = '儲存成功';
redirect('form.php'); // 重導向到 GET 頁面,防止重新整理重複提交
exit;
}
// GET 顯示表單與閃存訊息
$flash = $_SESSION['flash'] ?? '';
unset($_SESSION['flash']);
?>
選型決策
| 需求 | 推薦方式 |
| 一般頁面跳轉、API 重導向 | header() + exit |
| 需顯示中介提示頁(支付成功、表單送出) | Meta refresh 或 JS 延遲 |
| 需保留 Referer 給第三方統計 | JS 模擬點擊 |
| 表單提交後防重複提交 | PRG 模式 (header 302/303) |
| CLI 腳本 | 不可用 header,輸出文字提示 |