Friday, April 26, 2024

修改.htaccess實現301重定向

出於 SEO、PR 值傳遞、網址轉換的目的,在網站初建和網站遷移時我們都需要使用 301 重定向,通常包括域名對域名,目錄對目錄和一個獨立網址對另一個獨立網址的重定向。在虛擬主機上作 301 重定向,最常用的方法有2種:

1.直接編輯 .htaccess。

2.用 cPanel 設定。

實質二者都是修改文件 .htaccess,只是前者手工編輯,後者是由 cPanel 完成。用 cPanel 操作相當簡單,登陸你的 cPanel–>Domain–>Redirects,選擇相應的選項即可完成設置,這裡暫不討論。下面講一下直接編輯 .htaccess 的方法。

注意:在設置 301 重定向之前務必備份相應目錄下的.htaccess文件。

1.重定向domain.com到www.domain.com

這種重定向旨在使域名唯一,是網站SEO必須要做的,後面重定向www.domain.com到domain.com也是出於同樣的原因,只是形式不同。打開.htaccess文件,加入以下規則。(下面的規則是針對主域名的,子域名要修改)

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

2.重定向www.domain.com到domain.com

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

3.重定向olddomain.com到www.newdomain.com

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

4.重定向olddomain.com to newdomain.com

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

5.重定向domain.com/file/file.php 到 otherdomain.com/otherfile/other.php

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

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.