| 代碼 | 名稱 | SEO 影響 | 適用場景 |
|---|---|---|---|
| 301 | Moved Permanently | 權重傳遞 ~90-99%,舊網址從索引移除 | 網域遷移、HTTPS 強制、永久網址變更 |
| 302 | Found (暫時重導向) | 權重不傳遞,舊網址保留索引 | 維護頁面、A/B 測試、暫時活動頁 |
| 307 | Temporary Redirect | 同 302,但強制保持原請求方法(POST 不變 GET) | 表單提交後重導向 |
| 404 | Not Found | 權重歸零,頁面從索引移除 | 頁面確實不存在 |
<?php
// 方法一:簡單版(適用大多數情況)
header('HTTP/1.1 301 Moved Permanently');
header('Location: https://www.example.com/new-page');
exit;
// 方法二:嚴謹版(相容 HTTP/1.0 與 1.1)
$protocol = $_SERVER['SERVER_PROTOCOL'] ?? 'HTTP/1.0';
if (!in_array($protocol, ['HTTP/1.1', 'HTTP/1.0'])) {
$protocol = 'HTTP/1.0';
}
header("$protocol 301 Moved Permanently");
header('Location: https://www.example.com/new-page');
exit;
?>
<?php
// PHP 預設 header('Location:') 即發送 302
header('Location: https://www.example.com/maintenance');
exit;
// 明確指定 302(PHP 5.4+)
http_response_code(302);
header('Location: https://www.example.com/maintenance');
exit;
?>
<?php
header('HTTP/1.1 404 Not Found');
// 可選:包含自訂 404 頁面
include '404.html';
exit;
?>
Headers already sent 警告且重導向失效。<?php
/**
* 統一重導向助手
*/
function redirect(string $url, int $code = 302): never {
// 清除現有輸出緩衝
if (ob_get_level()) ob_clean();
// 設定狀態碼
http_response_code($code);
// 相容舊版 PHP
$protocol = $_SERVER['SERVER_PROTOCOL'] ?? 'HTTP/1.0';
$statusText = [
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
307 => 'Temporary Redirect',
308 => 'Permanent Redirect',
][$code] ?? '';
if ($statusText) {
header("$protocol $code $statusText");
}
header("Location: $url");
exit;
}
// 使用
redirect('https://example.com/new', 301); // 永久
redirect('https://example.com/temp', 302); // 暫時
?>
# 單一頁面永久轉移
Redirect 301 /old-page.html https://www.example.com/new-page.html
# 整個目錄永久轉移
Redirect permanent /old-folder/ https://www.example.com/new-folder/
# 正則批次:所有 .gif 改導向 .jpg
RedirectMatch 301 (.*).gif$ https://www.example.com/images/$1.jpg
# mod_rewrite 強制 HTTPS + www
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301,L]
server {
listen 80;
server_name example.com www.example.com;
return 301 https://www.example.com$request_uri;
}
server {
listen 443 ssl;
server_name example.com;
return 301 https://www.example.com$request_uri;
}
PHP 重導向核心只有三行:http_response_code()、header('Location: ...')、exit。選對 301/302 關係 SEO 存亡,務必在無輸出前呼叫。高流量站點建議前移至 Web Server 層處理。