重導向本質:伺服器回應 3xx 狀態碼 + Location 標頭,瀏覽器自動跳轉新 URL。PHP 透過 `header()` 發送原始 HTTP 標頭。
適用場景:網域遷移、網址結構永久變更、HTTP→HTTPS 強制、SEO 權重傳遞。
<?php
header('HTTP/1.1 301 Moved Permanently');
header('Location: https://www.example.com/');
exit();
<?php
$protocol = $_SERVER['SERVER_PROTOCOL'];
if (!in_array($protocol, ['HTTP/1.1', 'HTTP/1.0'], true)) {
$protocol = 'HTTP/1.0';
}
header("$protocol 301 Moved Permanently");
header('Location: https://www.example.com/');
exit();
適用場景:登入後跳回原頁、A/B 測試、維護頁暫時導向、多語言偵測導向。
<?php
// PHP 5.4+ 可省略狀態碼,預設 302
header('Location: https://www.example.com/login.php');
exit();
// 明確指定 302 (舊版相容)
header('HTTP/1.1 302 Found');
header('Location: https://www.example.com/login.php');
exit();
<?php
header('HTTP/1.1 404 Not Found');
// 可選:輸出自訂 404 頁面內容
include '404.html';
exit();
# 301 永久
Redirect 301 /old/old.htm https://www.example.com/new.htm
Redirect permanent /one https://example.com/two
RedirectMatch 301 (.*).gif$ https://www.example.com/images/$1.jpg
# mod_rewrite 規則 (功能更強)
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.net$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]
# 302 暫時
Redirect 302 /temp /maintenance.html
RewriteRule ^promo$ /landing.php [R=302,L]
# 301
rewrite ^/old/(.*)$ https://www.example.com/new/$1 permanent;
# 302
rewrite ^/login$ /sso/login redirect;
PHP 重導向核心:header('HTTP/1.1 3xx ...') + header('Location: ...') + exit()。301 永久、302 暫時,語意正確才能兼顧 SEO 與使用者體驗。生產環境建議集中管理重導向規則 (中介層/反向代理/框架路由),避免分散在各 PHP 檔案中。