301 是 HTTP 協議中「永久重定向」狀態碼的代號,代表使用者請求的頁面已經永久遷移到新的位址。當伺服器回傳這個狀態時,瀏覽器或搜尋引擎蜘蛛會自動轉往新的位置。在 SEO 實務中,301 是最被推崇的網址搬移方式,它能夠集中權重、平滑轉移站點的分量,避免舊連結的權重白白流失。
以下整理了常見伺服器環境下實作 301 的方法,並以 semshare.net 為示範網域。
開啟「網際網路資訊服務管理員」→ 選取虛擬目錄 → 點選「重定向到 URL」,填入目標位址,再勾選「資源的永久重定向」即可。
<%@ %>
< %
Response.Status=”301 Moved Permanently”
Response.AddHeader “Location”, “https://www.sem.cm/articles/301/”
%>
<script runat=”server”>
private void Page_Load(object sender, System.EventArgs e)
{
Response.Status = “301 Moved Permanently”;
Response.AddHeader(”Location”,”https://www.sem.cm/articles/301/“);
}
< /script>
header(”HTTP/1.1 301 Moved Permanently”);
header(”Location: https://www.sem.cm/articles/301/”);
exit();
$q = new CGI;
print $q->redirect(”https://www.sem.cm/”);
<%
response.setStatus(301);
response.setHeader( “Location”, “https://www.sem.cm/” );
response.setHeader( “Connection”, “close” );
%>
新建 .htaccess 檔案,寫入以下內容(需先啟用 mod_rewrite):
1)將不帶 WWW 的網域轉向到帶 WWW 的網域
Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^semshare.net [NC]
RewriteRule ^(.*)$ https://www.sem.cm/$1 [L,R=301]
2)整站重定向到新網域
Options +FollowSymLinks
RewriteEngine on
RewriteRule ^(.*)$ https://www.sem.cm/$1 [L,R=301]
3)以正則表達式實作 301,達成偽靜態
Options +FollowSymLinks
RewriteEngine on
RewriteRule ^news-(.+).html$ news.php?id=$1
如此可將 news.php?id=123 形式的位址對應到 news-123.html。
為了讓網址正規化,SEO 通常會把不帶 WWW 的網域轉向到帶 WWW 的網域,vhosts.conf 可寫成:
<VirtualHost *:80>
ServerName www.sem.cm
DocumentRoot /home/semshare
< /VirtualHost>
<VirtualHost *:80>
ServerName semshare.net
RedirectMatch permanent ^/(.*) https://www.sem.cm/$1
< /VirtualHost>
此外,部分 IDC 服務商會提供自訂 301 的控制面板,可依實際狀況靈活運用。
設定完成後,別忘了測試跳轉是否正確,以下兩個工具可檢測 301 的實作情形:
https://www.seoconsultants.com/tools/headers.asp
https://www.internetofficer.com/seo-tool/redirect-check/