以下把常見語言與伺服器環境的 301 實作方式整理成一份對照表,方便依專案狀況直接取用(實際使用時請把「https://主域名/」換成你的目標網址)。
%@ Language=VBScript % % Response.Status = "301 Moved Permanently" Response.AddHeader "Location", "https://主域名/" %
<script runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location", "https://主域名/");
}
</script>
header("HTTP/1.1 301 Moved Permanently");
header("Location: https://主域名/");
exit();
$q = new CGI;
print $q->redirect("https://主域名/");
% response.setStatus(301); response.setHeader( "Location", "https://主域名/" ); response.setHeader( "Connection", "close" ); %
新建 .htaccess 檔案並寫入以下內容(需先開啟 mod_rewrite)。
把不帶 WWW 的網域導向帶 WWW 的網域:
Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^域名 [NC]
RewriteRule ^(.*)$ https://主域名/$1 [L,R=301]
整站重定向到新網域:
Options +FollowSymLinks RewriteEngine on RewriteRule ^(.*)$ https://主域名/$1 [L,R=301]
為了 URL 正規化,SEO 上通常會把不帶 WWW 的網域導向帶 WWW 的網域,在 vhosts.conf 中可以這樣寫:
<VirtualHost *:80> ServerName 主域名 DocumentRoot /home/www </VirtualHost> <VirtualHost *:80> ServerName 你的舊域名 RedirectMatch permanent ^/(.*) https://主域名/$1 </VirtualHost>