301 永久重定向對 SEO 至關重要,但在 Windows 虛擬主機或 VPS 環境下,往往無法直接在 IIS 設定整站重定向。本文提供兩種純程式碼層面的解決方案,適用於 ASP.NET 應用程式。
若主機支援 IIS 7.0+ 且已安裝 URL Rewrite 模組,可在根目錄 Web.config 的 <system.webServer> 區段加入重寫規則,將無 www 的網域導向帶 www 的網域。
<system.webServer>
<rewrite>
<rules>
<rule name="Redirect" stopProcessing="true">
<match url=".*" />
<conditions>
<add input="{HTTP_HOST}" pattern="^jb51.net$" />
</conditions>
<action type="Redirect" url="https://www.jb51.net/{R:0}" redirectType="Permanent" />
</rule>
</rules>
</rewrite>
</system.webServer>
對於仍使用 IIS 6.0 的虛擬主機,可建立一個實作 IHttpModule 的類別,在 AuthorizeRequest 事件中攔截請求並發出 301 回應。
using System;
using System.Web;
using System.Configuration;
namespace SiteSense.Domain
{
public class DomainLocation : IHttpModule
{
public void Dispose() { }
public void Init(HttpApplication context)
{
context.AuthorizeRequest += (sender, e) => Process301(sender, e);
}
private void Process301(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
HttpRequest request = app.Context.Request;
string requestedHost = request.Url.DnsSafeHost;
string domain = ConfigurationManager.AppSettings["WebDomain"]; // 例: jb51.net
string targetDomain = ConfigurationManager.AppSettings["URL301Location"]; // 例: www.jb51.net
// 若請求主機包含非 www 網域,且不包含目標網域,則導向
if (requestedHost.IndexOf(targetDomain) == -1 && requestedHost.IndexOf(domain) != -1)
{
app.Response.StatusCode = 301;
app.Response.AddHeader("Location",
requestedHost.Replace(requestedHost, "https://" + targetDomain + request.RawUrl.Trim()));
app.Response.End();
}
}
}
}
<appSettings>
<add key="WebDomain" value="jb51.net" />
<add key="URL301Location" value="www.jb51.net" />
</appSettings>
<system.web>
<httpModules>
<add name="DomainLocation" type="SiteSense.Domain.DomainLocation, SiteSense.Domain" />
</httpModules>
</system.web>
完成部署後,可使用線上 HTTP Header 檢測工具 (如 https://www.jb51.net/http_header/) 確認回應狀態碼為 301。