首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

Windows 虛擬主機與 VPS 實現 301 重定向的兩種方案 (ASP.NET)

     編輯:ASP.NET 基礎

前言

301 永久重定向對 SEO 至關重要,但在 Windows 虛擬主機或 VPS 環境下,往往無法直接在 IIS 設定整站重定向。本文提供兩種純程式碼層面的解決方案,適用於 ASP.NET 應用程式。

方案一:透過 Web.config URL Rewrite 模組 (需 IIS 7.0 以上)

若主機支援 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>

方案二:使用 HttpModule 攔截實現 (相容 IIS 6.0)

對於仍使用 IIS 6.0 的虛擬主機,可建立一個實作 IHttpModule 的類別,在 AuthorizeRequest 事件中攔截請求並發出 301 回應。

步驟 1:建立 DomainLocation 類別

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();
            }
        }
    }
}

步驟 2:Web.config 註冊模組與應用程式設定

<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。

注意事項

  • 上述兩種方法僅適用於 ASP.NET 應用程式,不適用於傳統 ASP。
  • 方案一需主機支援 URL Rewrite 模組;方案二相容性較佳但需編譯部署 DLL。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved