Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> 電腦軟體教學 >> 伺服器技術 >> 關於伺服器

Apache .htaccess 實現 301 重定向:非 www 域名跳轉至 www 完整教學

編輯:關於伺服器

為了 SEO 權重集中、避免重複內容,需將裸域名 (example.com) 301 永久重定向至 www.example.com。Apache 可透過 mod_rewrite 或 mod_alias 在 .htaccess 實現,本文提供兩種寫法與模組啟用檢查。

環境確認

  • OS:Windows / Linux
  • Apache:2.2 / 2.4
  • 已啟用 mod_rewrite (見下文檢查步驟)

方法一: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 表示最後一條規則。

方法二:mod_alias (簡潔、不需正則、不保留路徑)

RedirectMatch 301 ^(.*)$ https://www.example.com

差異:RedirectMatch 會將所有路徑導向首頁,不保留原 URI;RewriteRule 保留路徑,對 SEO 更友善。

啟用 mod_rewrite 模組 (必要步驟)

編輯 httpd.conf (或 apache2.conf):

# 搜尋以下行,移除行首 # 號
LoadModule rewrite_module modules/mod_rewrite.so

# 若無此行,手動新增
LoadModule rewrite_module modules/mod_rewrite.so

儲存後重啟 Apache:

  • Windows:httpd -k restart 或服務管理員重啟
  • Linux: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

常見問題

HTTPS 版本範例 (保留協定、路徑、查詢字串)

RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteCond %{HTTPS} on
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301,QSA]

RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301,QSA]

QSA (Query String Append) 自動保留原查詢參數。

完成配置並驗證無誤後,裸域名所有流量將 301 永久導向 www 版本,搜尋引擎將合併權重,避免重複內容扣分。

Copyright © Windows教程網 All Rights Reserved
現象原因解決
重定向不生效AllowOverride None / mod_rewrite 未載入httpd.conf 設 AllowOverride All、載入 rewrite_module
無限循環重定向RewriteCond 寫錯匹配到 www 也觸發用 ^example\.com$ 錨定開頭結尾,或加 !^www\. 排除
HTTPS 站點仍跳 HTTP規則寫死 https://用 https:// 或 RewriteCond %{HTTPS} on 動態判斷