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

Linux服務器.htaccess實現301重定向完全指南

編輯:關於伺服器

301重定向:SEO權重傳遞與網址規範化利器

網站初建、遷移、域名整併時,301永久重定向可傳遞PR值、統一入口、避免重複內容懲罰。Linux虛擬主機主流透過編輯 .htaccess 實現(cPanel本質同樣修改此檔)。操作前務必備份原檔。

五大常見重定向規則範本

1. 非www導向www(主域名,含子域名保護)

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

進階版(排除子域名):

RewriteEngine On
RewriteCond %{HTTP_HOST} !^(www\.45it\.com|t\.webjx\.com)$ [NC]
RewriteRule ^(.*)$ https://www.45it.com$1 [L,R=301]

邏輯:除列出域名外全導向,支持多子域名在條件行以 | 分隔新增。

2. www導向非www

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

3. 舊域名導向新域名(保留路徑)

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

4. 舊域名導向新域名(含RewriteBase)

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !olddomain\.com$ [NC]
RewriteRule ^(.*)$ https://newdomain.com$1 [L,R=301]

5. 單檔案/目錄精準導向

RewriteCond %{HTTP_HOST} ^www\.domain\.com$
RewriteRule ^file/file\.php$ https://www.otherdomain.com/otherfile/other.php [R=301,L]

關鍵提醒

  • 僅適用支援 .htaccess 的Linux系統,Windows主機請尋其他方案。
  • 正則表達式核心:%{HTTP_HOST} 匹配域名,$1 保留原路徑,[NC] 不區分大小寫,[L,R=301] 最後一條規則+301狀態碼。
  • 子域名處理靈活運用 | 分隔排除清單。

驗證建議

設定後使用線上工具(如HTTP狀態碼檢測器)確認返回301且Location頭正確,配合Google Search Console提交變更通知,加速權重轉移。

Copyright © Windows教程網 All Rights Reserved