為了 SEO 權重集中、避免重複內容,需將裸域名 (example.com) 301 永久重定向至 www.example.com。Apache 可透過 mod_rewrite 或 mod_alias 在 .htaccess 實現,本文提供兩種寫法與模組啟用檢查。
mod_rewrite (見下文檢查步驟)在網站根目錄 .htaccess 加入:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]
指令解析:
RewriteEngine On:啟用重寫引擎。RewriteCond %{HTTP_HOST} ^example\.com$ [NC]:條件匹配 Host 標頭為裸域名 (不區分大小寫)。RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]:捕獲完整路徑 $1,301 重定向至 www 同路徑,L 表示最後一條規則。RedirectMatch 301 ^(.*)$ https://www.example.com
差異:RedirectMatch 會將所有路徑導向首頁,不保留原 URI;RewriteRule 保留路徑,對 SEO 更友善。
編輯 httpd.conf (或 apache2.conf):
# 搜尋以下行,移除行首 # 號
LoadModule rewrite_module modules/mod_rewrite.so
# 若無此行,手動新增
LoadModule rewrite_module modules/mod_rewrite.so
儲存後重啟 Apache:
httpd -k restart 或服務管理員重啟systemctl restart httpd / apache2ctl restart# 檢查狀態碼與 Location 標頭
curl -I https://example.com/
# 預期輸出
HTTP/1.1 301 Moved Permanently
Location: https://www.example.com/
# 檢查路徑保留
curl -I https://example.com/path/to/page
# 預期輸出
HTTP/1.1 301 Moved Permanently
Location: https://www.example.com/path/to/page
| 現象 | 原因 | 解決 |
|---|---|---|
| 重定向不生效 | AllowOverride None / mod_rewrite 未載入 | httpd.conf 設 AllowOverride All、載入 rewrite_module |
| 無限循環重定向 | RewriteCond 寫錯匹配到 www 也觸發 | 用 ^example\.com$ 錨定開頭結尾,或加 !^www\. 排除 |
| HTTPS 站點仍跳 HTTP | 規則寫死 https:// | 用 https:// 或 RewriteCond %{HTTPS} on 動態判斷 |