萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 實作 301 永久重導向與 302 暫時重導向完整指南

HTTP 重導向核心原理

重導向本質:伺服器回應 3xx 狀態碼 + Location 標頭,瀏覽器自動跳轉新 URL。PHP 透過 `header()` 發送原始 HTTP 標頭。

301 Moved Permanently (永久重導向)

適用場景:網域遷移、網址結構永久變更、HTTP→HTTPS 強制、SEO 權重傳遞。

寫法 1:簡潔版 (現代瀏覽器通用)

<?php
header('HTTP/1.1 301 Moved Permanently');
header('Location: https://www.example.com/');
exit();

寫法 2:相容 HTTP/1.0 與 1.1 (嚴謹版)

<?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();

302 Found (暫時重導向)

適用場景:登入後跳回原頁、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();

404 Not Found 附帶示範

<?php
header('HTTP/1.1 404 Not Found');
// 可選:輸出自訂 404 頁面內容
include '404.html';
exit();

關鍵注意事項

  • header() 必須在任何輸出前呼叫 (含空白、BOM、echo、HTML),否則「Headers already sent」警告且重導向失效。
  • exit()/die() 終止腳本,避免後續碼繼續執行產生副作用。
  • Location 值必須為絕對 URL (RFC 7231),雖然瀏覽器容錯相對路徑,但標準要求完整 `https://domain/path`。
  • 301 會被瀏覽器/搜尋引擎快取,測試時用 302,確定無誤再改 301。
  • SEO 影響:301 傳遞 ~90-99% Link Equity,302 不傳遞 (Google 現今若長期 302 可能視為 301)。

Apache .htaccess 對應寫法 (對照參考)

# 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]

Nginx 設定對照

# 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 檔案中。

copyright © 萬盛學電腦網 all rights reserved