PHP 實現頁面跳轉主要依賴 header() 函數發送 HTTP Location 標頭。本文整理了從基礎跳轉到帶參數跳轉、SEO 友好的 301 永久重定向等常見場景的實現代碼。
<?php
// 跳轉到絕對 URL
header("Location: https://www.example.com/");
// 跳轉到相對路徑
header("Location: index123.php");
?>
關鍵點:header() 必須在任何輸出(包括空白、HTML、echo)之前調用,否則會觸發「Headers already sent」警告並導致跳轉失效。
常見於短網址、外鏈跳轉頁:
<?php
$url = $_GET['url'] ?? ''; // 獲取目標 URL
// 建議驗證 $url 合法性,防止開放式重定向攻擊
if (filter_var($url, FILTER_VALIDATE_URL)) {
header("Location: $url");
exit; // 跳轉後務必終止腳本
}
?>
訪問 url.php?url=https://www.baidu.com 即可跳轉至百度。
當域名遷移、網頁地址永久變更時,必須使用 301 狀態碼告知搜尋引擎權重轉移:
<?php
$targetUrl = 'https://www.newdomain.com' . $_SERVER['REQUEST_URI'];
header("HTTP/1.1 301 Moved Permanently");
header("Location: $targetUrl");
exit;
?>
使用 curl -I 檢查回應標頭:
# curl -I https://olddomain.com/page
HTTP/1.1 301 Moved Permanently
Location: https://www.newdomain.com/page
...
<?php
$host = $_SERVER['HTTP_HOST'];
$requestUri = $_SERVER['REQUEST_URI'] ?? '';
if ($host !== 'www.example.com') {
header('HTTP/1.1 301 Moved Permanently');
header("Location: https://www.example.com$requestUri");
exit;
}
?>
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]
header() 前無任何輸出,必要時用 ob_start() 開啟輸出緩衝。exit,防止後續代碼繼續執行。掌握 header("Location: ...") 基礎用法、301 狀態碼正確發送、參數化跳轉與安全防護,即可應對絕大多數 PHP 頁面跳轉場景。對於全站域名規範化,推薦在 Web 服務器層面(Nginx/Apache)配置,效能更優。