Search code examples
c#asp.nethttp-redirectcanonical-name

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


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.com to www.example.com

Stackoverflow.com is already doing this, I know there is a premade mechanism in PHP (.htaccess) file. But how to do it in asp.net ?

Thanks


Solution

  • 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:

    <httpModules>
      [...]
      <add type="[Namespace.]SeoUrls, [AssemblyName], [Version=x.x.x.x, Culture=neutral, PublicKeyToken=933d439bb833333a]" name="SeoUrls"/>
    </httpModules>
    

    This method works quite well for us.