asp.net uses Web.config to implement 301 permanent redirection of the entire site

1. Add configuration in web.config

  <appSettings>
    <add key="WebDomain" value="mhzg.net"/>
    <add key="URL301Location" value="www.mhzg.net"/>
  </appSettings>

2. Create a new class library project under the current solution

3. Create a new cs and name it: Domain301.cs

using System;
using System.Web;
using System.Configuration;
namespace Domain
{
    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();
            }
        }
    }
}

4. Register in web.config

<httpModules>
      <add name="Redirect301" type="RedirectNewDomain, Domain"  />
</httpModules>







Guess you like

Origin blog.csdn.net/gaoxu529/article/details/45916263