方案一:Apache .htaccess(最常用、效能最好)
# 開啟重寫引擎
RewriteEngine On
# 強制 www(非 www 導向 www)
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]
# 強制 HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
# 移除 index.php
RewriteCond %{THE_REQUEST} ^[A-Z]+\ /index\.php[/?\s] [NC]
RewriteRule ^index\.php(.*)$ /$1 [R=301,L,NC]
# 統一斜線結尾(目錄)
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.*[^/])$ /$1/ [R=301,L]
方案二:Nginx 配置
server {
listen 80;
server_name example.com www.example.com;
# 強制 HTTPS
return 301 https://www.example.com$request_uri;
}
server {
listen 443 ssl http2;
server_name example.com;
# 非 www 導向 www
return 301 https://www.example.com$request_uri;
}
server {
listen 443 ssl http2;
server_name www.example.com;
# 移除 index.php
location / {
try_files $uri $uri/ /index.php?$query_string;
}
# 避免雙斜線
merge_slashes on;
}
方案三:PHP 代碼(共用主機無法改 Web Server 時)
<?php
// 必須在任何輸出之前執行
function redirect301(string $url, int $code = 301): never {
// 防止 Header 已發送
if (headers_sent($file, $line)) {
error_log("Headers already sent in $file:$line, cannot redirect");
// 降級:JS 跳轉
echo "<script>location.replace('$url');</script>";
exit;
}
http_response_code($code);
header("Location: $url", true, $code);
// 防止繼續執行
exit;
}
// 使用範例:強制 www + HTTPS
$host = $_SERVER['HTTP_HOST'] ?? '';
$uri = $_SERVER['REQUEST_URI'] ?? '/';
$proto = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$targetHost = 'www.example.com';
$targetProto = 'https';
if ($host !== $targetHost || $proto !== $targetProto) {
$newUrl = "$targetProto://$targetHost$uri";
redirect301($newUrl);
}
// 移除 index.php
if (str_starts_with($uri, '/index.php')) {
$newUri = substr($uri, 9); // 移除 '/index.php'
if ($newUri === '') $newUri = '/';
redirect301("https://$targetHost$newUri");
}
?>
常見重定向場景對照表
| 場景 | .htaccess 規則 | PHP 判斷邏輯 |
| 非 www → www | RewriteCond %{HTTP_HOST} ^domain\.com [NC] | $host !== 'www.domain.com' |
| HTTP → HTTPS | RewriteCond %{HTTPS} off | $_SERVER['HTTPS'] !== 'on' |
| 舊域名 → 新域名 | RewriteCond %{HTTP_HOST} ^old\.com [NC] | in_array($host, ['old.com','www.old.com']) |
| 移除 index.php | RewriteRule ^index\.php/(.*) /$1 [R=301,L] | str_starts_with($uri, '/index.php') |
| 舊路徑 → 新路徑 | RewriteRule ^old-path/(.*) /new-path/$1 [R=301,L] | str_starts_with($uri, '/old-path/') |
驗證與除錯
# 命令列驗證
curl -I https://example.com
# 應回傳:HTTP/1.1 301 Moved Permanently
# Location: https://www.example.com/
# 瀏覽器開發者工具 Network 面板:查看 301 狀態碼與 Location 標頭
# 線上工具
# https://www.redirect-checker.org/
# https://httpstatus.io/
SEO 關鍵點
- 301 傳遞 90-99% 鏈接權重(PageRank)
- 避免重定向鏈(A→B→C),直接 A→C
- 更新 Sitemap、內部連結、Canonical 標籤指向新 URL
- Google Search Console 提交變更通知
- 保持 301 至少 1 年以上再考慮移除