How to redirect with “www” URL's to without “www” URL's or vice-versa?

后端 未结 8 2047
死守一世寂寞
死守一世寂寞 2020-12-08 05:15

I am using ASP.NET 2.0 C#. I want to redirect all request for my web app with \"www\" to without \"www\"

www.example.com to example.com

Or

example.co

8条回答
  •  [愿得一人]
    2020-12-08 05:53

    I've gone with the following solution in the past when I've not been able to modify IIS settings.

    Either in an HTTPModule (probably cleanest), or global.asax.cs in Application_BeginRequest or in some BasePage type event, such as OnInit I perform a check against the requested url, with a known string I wish to be using:

    public class SeoUrls : IHttpModule
    {
      #region IHttpModule Members
    
      public void Init(HttpApplication context)
      {
          context.PreRequestHandlerExecute += OnPreRequestHandlerExecute;
      }
    
      public void Dispose()
      {
      }
    
      #endregion
    
      private void OnPreRequestHandlerExecute(object sender, EventArgs e)
      {
        HttpContext ctx = ((HttpApplication) sender).Context;
        IHttpHandler handler = ctx.Handler;
    
        // Only worry about redirecting pages at this point
        // static files might be coming from a different domain
        if (handler is Page)
        {
          if (Ctx.Request.Url.Host != WebConfigurationManager.AppSettings["FullHost"])
          {
            UriBuilder uri = new UriBuilder(ctx.Request.Url);
    
            uri.Host = WebConfigurationManager.AppSettings["FullHost"];
    
            // Perform a permanent redirect - I've generally implemented this as an 
            // extension method so I can use Response.PermanentRedirect(uri)
            // but expanded here for obviousness:
            response.AddHeader("Location", uri);
            response.StatusCode = 301;
            response.StatusDescription = "Moved Permanently";
            response.End();
          }
        }
      }
    }
    

    Then register the class in your web.config:

    
      [...]
      
    
    

    This method works quite well for us.

提交回复
热议问题