PHP 實現頁面跳轉主要有三大類方式,各有適用場景與限制。本文系統整理 header()、JavaScript、HTML Meta Refresh 等跳轉技術,並重點分析常見錯誤與最佳實踐。
<?php
// 標準跳轉
$url = "https://example.com/page.php";
header("Location: $url");
exit; // 關鍵:防止後續代碼繼續執行
?>
<?php
$url_this = strtolower('https://' . $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"]);
$go_url = str_replace('https://www.old-domain.com/blog', 'https://www.new-domain.com', $url_this);
header("Location: $go_url");
exit;
?>
void header(string $header, bool $replace = true, int $http_response_code = 0)
$replace:是否替換同類型頭信息,默認 true$http_response_code:強制設置 HTTP 狀態碼(如 301 永久重定向、302 臨時重定向)header("Location: $url") ✓ | header("Location : $url") ✗<?php
$url = "https://example.com";
echo "<script>window.location.href='$url';</script>";
// 或帶延遲
echo "<script>setTimeout(function(){window.location.href='$url';}, 3000);</script>";
?>
<meta http-equiv="refresh" content="秒數; url=目標網址" />
<!-- 5秒後刷新本頁 -->
<meta http-equiv="refresh" content="5" />
<!-- 5秒後跳轉到首頁 -->
<meta http-equiv="refresh" content="5; url=https://example.com" />
<!-- 立即跳轉(0秒) -->
<meta http-equiv="refresh" content="0; url=https://example.com" />
<!-- 表單頁 -->
<form action="process.php" method="post">
<input type="text" name="name" />
<input type="submit" name="submit" value="提交" />
</form>
<!-- process.php 處理邏輯 -->
<?php
if (isset($_POST["name"])) {
// 業務處理...
header("Location: success.php?name=" . urlencode($_POST["name"]));
exit;
}
?>
注意:處理頁面不能有任何輸出,否則 header 失效報錯。
| 狀態碼 | 含義 | 適用場景 | SEO 影響 |
|---|---|---|---|
| 301 | Moved Permanently | 域名遷移、URL 永久變更 | 傳遞權重,搜索引擎更新索引 |
| 302 | Found (臨時重定向) | 登錄後跳轉、臨時維護頁面 | 不傳遞權重,保留原 URL 索引 |
| 303 | See Other | POST 請求處理後跳轉 | 強制 GET 請求,防止重複提交 |
| 307 | Temporary Redirect | 保持原請求方法的臨時跳轉 | 保持 POST 數據,現代瀏覽器支持 |
<?php
// 永久重定向(SEO 友好)
header("Location: https://new-domain.com", true, 301);
exit;
// POST 後跳轉(防重複提交)
header("Location: success.php", true, 303);
exit;
?>
掌握這些技巧,能應對從簡單頁面跳轉到複雜 OAuth 回調、支付回調、多域名遷移等各類場景。