asp.net 利用Web.config的HttpModule 實現整站301永久重新導向(簡單方便)

來源:互聯網
上載者:User

之前是做301定向是在每個頁面調用一個方法的,原文http://www.cnblogs.com/hakuci/archive/2010/11/19/1881681.html

現在利用Web.config的HttpModule 實現整站301永久重新導向

具體方法如下:
1在web.config加入配置

<configuration>
  <appSettings>
    <add key="WebDomain" value="wecanwecan.com"/>
    <add key="URL301Location" value="www.wecanwecan.com"/>
  </appSettings>

2,在當前解決方案下建立一個類庫項目
3,建立一個cs,我這裡粗陋的命名一下:ChangeDomain.cs

using System;
using System.Web;

using System.Configuration;

namespace ChangeDomain
{

public class RedirectNewDomain : IHttpModule
    {
        public void Dispose()
        {
        }
        public void Init(HttpApplication context)
        {
            context.AuthorizeRequest += (new EventHandler(Process301));
        }
        public void Process301(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            HttpRequest request = app.Context.Request;
            string lRequestedPath = request.Url.DnsSafeHost.ToString();
            string strDomainURL = ConfigurationManager.AppSettings["WebDomain"].ToString();
            string strWebURL = ConfigurationManager.AppSettings["URL301Location"].ToString();
            if (lRequestedPath.IndexOf(strWebURL) == -1)
            {
                app.Response.StatusCode = 301;
                app.Response.AddHeader("Location", lRequestedPath.Replace(lRequestedPath, "http://" + strWebURL + request.RawUrl.ToString().Trim()));  //這裡面的網域名稱根據自己的實際情況修改
                app.Response.End();
            }
        }
    }
}

寫完這個基本就ok了。剩下的就是在web.config裡註冊一下就好了。

 

<httpModules>
<add name="ChangeDomain" type="ChangeDomain.RedirectNewDomain, ChangeDomain" />
</httpModules>

上面的命名也是我這邊的粗陋命名,具體的web.config註冊寫法如下:

<add name="隨便命名" type="HttpModule命名空間加類名,dll檔案名稱" />

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.