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
<rewrite>
    <rules>
        <rule name="NonWWWtoWWW" stopProcessing="true">
            <match url=".*" ignoreCase="true" />
            <conditions>
                <add input="{HTTP_HOST}" pattern="^mywebsite\.com$" />
            </conditions>
            <action type="Redirect" redirectType="Permanent" url="https://www.mywebsite.com/{R:0}" />
        </rule>
    </rules>
<rewrite>

Let's understand the above configuration:

The <rewrite> section can contain <rules></rules> section to add one or more rules to redirect or rewrite URLs. It can also contain <rewriteMaps></rewriteMaps> to map old URLs to new URLs.

The <rules> section can contain one or more rules for url rewrite/redirect. The section is used to define the logic of what to compare or match the request URL with, and what to do if the comparison is successful.

The <rule name="NonWWWtoWWW" stopProcessing="true"> specifies the rule which will redirect from non-www to the “www” version of your website. The name attribute specifies the name of a rule. The stopProcessing attribute specifies whether to process subsequent rules or not, after the rule action is performed. Here, stopProcessing=”true” will stop processing the next rules (if any) if the incoming URL is matched with the specified condition and redirect action is performed.

Each rule contains a match, conditions, and action section. The <match> node is used to specify either the regular expression or a wildcard pattern that is used to match URL strings.

The <match url=".*" ignoreCase="true" /> matches all URLs where this rule will be applicable. The .* is a wildcard pattern that allows all URLs.

The optional <conditions> section is used to specify additional logical operations to perform if a URL string matches the rule pattern. Here, you can check for certain values of HTTP headers or server variables.

<add input="{HTTP_HOST}" pattern="^mywebsite\.com$" /> specifies the HTTP_HOST is a server variable that points to your domain name e.g. http(s)://host:port/path?querystring

The pattern attribute specifies the pattern to compare. pattern="^mywebsite\.com$" check whether the URL is mywebsite.com without www.

If this condition is passed then it will perform the specified action in the <action> section; otherwise, continue with the next rule.

The <action type="Redirect" redirectType="Permanent" url="https://www.mywebsite.com/{R:0}" /< specifies to redirect a request to a new URL https://www.mywebsite.com/{R:0} with the status code 301 (permanent redirect). {R:0} is the back-references to rule patterns that returns matched string.

Thus, the above rule will redirect any non-www URL of http(s):///mywebsite.com to https://www.mywebsite.com.

Ignore localhost Requests

You can ignore localhost requests to redirect to www URLs in your development machine by adding a condition, as shown below.

Example: Ignore localhost
<rewrite>
    <rules>
        <rule name="NonWWWtoWWW" stopProcessing="true">
            <match url=".*" ignoreCase="true" />
            <conditions>
				<add input="{HTTP_HOST}" pattern="localhost" negate="true"/>
                <add input="{HTTP_HOST}" pattern="^mywebsite\.com$" />
            </conditions>
            <action type="Redirect" redirectType="Permanent" url="https://www.mywebsite.com/{R:0}" />
        </rule>
    </rules>
<rewrite>

Redirect Requests in global.asax

You can redirect HTTP requests at the ASP.NET level by handling the Application_BeginRequest event in global.asax, as shown below.

Example: global.asax.cs
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.