頁面跳轉是 Web 開發基礎操作,PHP 提供多種實作方式,各有適用場景與注意事項。本文系統整理三大主流方案,並提供可直接落地的程式碼範本與最佳實踐。
<?php
// 302 暫時重導向(預設)
header('Location: https://example.com/target.php');
exit; // 關鍵:防止後續程式碼繼續執行
// 301 永久重導向(SEO 傳遞權重)
header('HTTP/1.1 301 Moved Permanently');
header('Location: https://example.com/new-url');
exit;?>
<?php
$host = $_SERVER['HTTP_HOST'] ?? '';
$routes = [
'www.a.com' => '/a/index.php',
'www.b.com' => '/b/index.php',
'www.c.com' => '/c/index.php',
];
if (isset($routes[$host])) {
header('Location: ' . $routes[$host], true, 302);
exit;
}
// 預設處理
header('Location: /default.php');
exit;?>
exit 或 die():否則腳本繼續執行,可能導致資料庫寫入、Session 變更等副作用ob_start(),並在重導向前 ob_end_clean()<?php
$url = 'https://example.com/target.php';
$delay = 3; // 秒
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="refresh" content="<?= $delay ?>;url=<?= htmlspecialchars($url, ENT_QUOTES, 'UTF-8') ?>">
<title>頁面跳轉中...</title>
</head>
<body>
<p><?= $delay ?> 秒後自動跳轉至 <a href="<?= htmlspecialchars($url, ENT_QUOTES, 'UTF-8') ?>">目標頁面</a></p>
</body>
</html>
header()<?php
$url = 'https://example.com/target.php';
?>
<script>
// 立即跳轉(取代當前歷史記錄,避免「上一頁」問題)
window.location.replace('<?= htmlspecialchars($url, ENT_QUOTES, 'UTF-8') ?>');
// 或延遲跳轉
// setTimeout(() => window.location.href = '...', 3000);
</script>
<noscript>
<meta http-equiv="refresh" content="0;url=<?= htmlspecialchars($url, ENT_QUOTES, 'UTF-8') ?>">
</noscript>
<?php
$target = 'https://example.com/order.php';
$params = [
'id' => 12345,
'action' => 'pay',
'token' => bin2hex(random_bytes(16)),
];
$url = $target . '?' . http_build_query($params);
?>
<script>window.location.replace('<?= htmlspecialchars($url, ENT_QUOTES, 'UTF-8') ?>');</script>
| 維度 | Header | Meta Refresh | JavaScript |
|---|---|---|---|
| 執行端 | 伺服器 | 客戶端 | 客戶端 |
| HTTP 狀態碼 | 301/302/303/307/308 | 200 | 200 |
| SEO 傳遞權重 | 是 (301/308) | 否 | 否 |
| 需在輸出前 | 是 | 否 | 否 |
| 可攜帶 POST 資料 | 否 (需 Session/Token) | 否 | 否 (可用 form.submit()) |
| 歷史記錄處理 | 瀏覽器決定 | 保留中介頁 | 可用 replace() 移除 |
| 適用場景 | 表單提交後、登入驗證、API 重導、SEO 遷移 | 靜態頁、維護通知、倒數提示 | AJAX 回調、條件判斷、動態參數、SPA 路由 |
header() + exit,符合 HTTP 標準、SEO 友善、效能最佳function redirect(string $url, int $status = 302): never {
// 可在此記錄存取日誌、驗證 URL 白名單等
header('Location: ' . $url, true, $status);
exit;
}
$_GET['redirect'] 未經過濾header('Location: ...'),應回傳 {"redirect": "url"} 由前端處理掌握三種跳轉方案的差異與適用場景,並遵循「優先 Header、次之 Meta/JS、封裝統一、安全第一」原則,即能在各種業務情境下優雅、安全地實作頁面跳轉。