Tutorialsteacher

Follow Us

Redirect non-www to www domain in asp.net

In ASP.NET MVC, you can redirect all HTTP requests from non-www to "www" version of your domain/website in two ways:

  1. Using the web.config
  2. Using global.asax

Redirect from non-www to www using the web.config

You can add rules for redirecting or rewriting HTTP requests at the IIS level in the web.config. This is the best place to redirect or rewrite URLs for your website.

Add the redirect rules in the <rewrite><rewrite> section of <system.webServer> section in the web.config.

Example: Redirect Rule in web.config
void Application_BeginRequest(object sender, EventArgs e)
{
    if (!Context.Request.Url.Authority.StartsWith("www") && !Context.Request.IsLocal)            
    {
        var url = string.Format("https://www.{0}{1}",
                        Context.Request.Url.Authority,
                        Context.Request.Url.PathAndQuery);
            
        Response.RedirectPermanent(url, true);
    }
}

Visit URL rewrite module for more information.