HTTP 狀態碼 **301 Moved Permanently** 告訴瀏覽器與搜尋引擎:資源**永久移動**至新 URL。搜尋引擎會將舊 URL 的權重 (PageRank、收錄、錨文字) **傳遞** 給新 URL,是域名遷移、網站改版、HTTPS 強制、WWW 統一、URL 結構調整的**唯一正規作法**。
<?php
// 必須在**任何輸出之前**執行 (含空白、BOM、HTML)
$newDomain = 'https://newdomain.com';
$requestUri = $_SERVER['REQUEST_URI'];
$targetUrl = $newDomain . $requestUri;
// 發送 301 標頭
header("HTTP/1.1 301 Moved Permanently", true, 301);
header("Location: $targetUrl");
header("Connection: close"); // 建議關閉連線
exit(); // 關鍵:終止後續腳本執行
?>
進階:條件式導向 (如僅導向特定目錄、保留查詢字串、排除特定路徑) 皆可在 PHP 中靈活實現。
RewriteEngine On
# 強制 HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
# 強制 WWW (或非 WWW)
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]
# 域名遷移 (保留完整路徑與查詢字串)
RewriteCond %{HTTP_HOST} ^old\.com$ [NC,OR]
RewriteCond %{HTTP_HOST} ^www\.old\.com$ [NC]
RewriteRule ^(.*)$ https://new.com/$1 [R=301,L,QSA]
放入網站根目錄 .htaccess 或虛擬主機配置 <VirtualHost> 內。需啟用 mod_rewrite 且 AllowOverride All。
server {
listen 80;
server_name old.com www.old.com;
# 全站 301 至新域名,保留 URI 與查詢字串
return 301 https://new.com$request_uri;
}
# 或特定目錄導向
location /old-section/ {
return 301 https://new.com/new-section$request_uri;
}
return 301 為 Nginx 原生指令,效能優於 rewrite,無正則開銷。
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="Redirect Old Domain" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTP_HOST}" pattern="^old\.com$" />
<add input="{HTTP_HOST}" pattern="^www\.old\.com$" />
</conditions>
<action type="Redirect" url="https://new.com/{R:1}" redirectType="Permanent" />
</rule>
<!-- 強制 HTTPS -->
<rule name="Force HTTPS" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTPS}" pattern="^OFF$" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
或使用 IIS 管理員 → 「URL 重寫」模組 → 新增規則 → 範本「標準重寫」→ 動作類型選「重導向」→ 重導向類型「永久 (301)」。
# cURL 檢查回應標頭 curl -I https://old.com/some/page # 預期輸出: # HTTP/1.1 301 Moved Permanently # Location: https://new.com/some/page # Content-Length: 0 # Connection: close # 線上工具: httpstatus.io, redirect-checker.org, SEO 擴充功能 (Redirect Path, Ayima)
SPA 使用 History API,伺服器需將所有非靜態資源請求導向 index.html,**不可使用 301** (會破壞客戶端路由)。正確配置:
# Nginx
location / {
try_files $uri $uri/ /index.html;
}
# Apache .htaccess
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.html [L]
301 重導向是 SEO 遷移的基石,正確實作與驗證,守住您辛苦累積的搜尋資產。