Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net mvc: How to redirect a non www to www and vice versa

People also ask

How do I redirect www to non www in web config?

Use IIS rewrite rule to redirect (301) all www requests to non-www. Code first, talks later. Replace the “yourdomain” with your domain name and add it under the system. webServer section in the Web.


You might consider a different approach:

protected void Application_BeginRequest (object sender, EventArgs e)
{
   if (!Request.Url.Host.StartsWith ("www") && !Request.Url.IsLoopback)
   {
      UriBuilder builder = new UriBuilder (Request.Url);
      builder.Host = "www." + Request.Url.Host;
      Response.Redirect (builder.ToString (), true);
   }
}

This will however do a 302 redirect so a little tweak is recommended:

protected void Application_BeginRequest (object sender, EventArgs e)
{
   if (!Request.Url.Host.StartsWith ("www") && !Request.Url.IsLoopback)
   {
      UriBuilder builder = new UriBuilder (Request.Url);
      builder.Host = "www." + Request.Url.Host;
      Response.StatusCode = 301;
      Response.AddHeader ("Location", builder.ToString ());
      Response.End ();
   }
}

This one will return 301 Moved Permanently.


if you copied it directly then you have incorrect markup in your web.config

you need

<system.webServer> 
    <rewrite>
      <rules>
        <rule name="Remove WWW prefix" > 
        <match url="(.*)" ignoreCase="true" /> 
        <conditions> 
        <add input="{HTTP_HOST}" pattern="^www\.domain\.com" /> 
        </conditions> 
        <action type="Redirect" url="http://domain.com/{R:1}" 
            redirectType="Permanent" /> 
        </rule> 
      </rules>
    </rewrite>
<system.webServer>

The line that says

<system.webServer> / <rewrite> / <rules> 

is stating that you need to put the config in that location within your web.Config.
<system.webServer> is one of the configSections of your web.Config file.

EDIT:

Make sure you first have the URL Rewrite module installed for IIS7

The page above talks about redirecting HTTP to HTTPS, but the concept still applies for WWW to non WWW

Also, here is some detailed information on how it all comes together.


    **For a www to a non www Thanks @developerart**

protected void Application_BeginRequest(object sender, EventArgs e)
    {
        if (Request.Url.Host.StartsWith("www") && !Request.Url.IsLoopback)
        {
            UriBuilder builder = new UriBuilder(Request.Url);
            builder.Host = Request.Url.Host.Replace("www.","");
            Response.StatusCode = 301;
            Response.AddHeader("Location", builder.ToString());
            Response.End();
        }
    }

protected void Application_BeginRequest(object sender, EventArgs e)
{
    if (!this.Request.Url.Host.StartsWith("www") && !this.Request.Url.IsLoopback)
    {
        var url = new UriBuilder(this.Request.Url);
        url.Host = "www." + this.Request.Url.Host;
        this.Response.RedirectPermanent(url.ToString(), endResponse: true);
    }
}

Building on user 151323' answer, here the complete answer for Azure users who also want to prevent users from accessing the site from a azurewebsites.net subdomain (this goes into your Global.asax inside the main class (MvcApplication for MVC users)):

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        if (Request.Url.Host.StartsWith("YourSite.azurewebsites") && !Request.Url.IsLoopback)
        {
            Response.StatusCode = 301;
            Response.AddHeader("Location", "www.YourSite.com");
            Response.End();

            return;
        }


        if (!Request.Url.Host.StartsWith("www") && !Request.Url.IsLoopback)
        {
            UriBuilder builder = new UriBuilder(Request.Url);
            builder.Host = "www." + Request.Url.Host;
            Response.StatusCode = 301;
            Response.AddHeader("Location", builder.ToString());
            Response.End();
        }
    }

You can use for https and www redirect. (You need to change "example")

<system.webServer>
  <!-- For force ssl and www -->
  <rewrite>
    <rules>
      <!-- For force ssl -->
      <rule name="http to https" stopProcessing="true">
        <match url="(.*)" />
        <conditions>
          <add input="{HTTPS}" pattern="^OFF$" />
        </conditions>
        <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
      </rule>
      <!-- For force ssl -->
      <!-- For force www -->
      <rule name="redirect to www" stopProcessing="true">
        <match url="(.*)" />
        <conditions>
          <add input="{HTTP_HOST}"  pattern="^example\.com$" />
        </conditions>
        <action type="Redirect" url="https://www.{HTTP_HOST}/{R:0}" redirectType="Permanent" />
      </rule>
      <!-- For force www -->
    </rules>
  </rewrite>
  <!-- For force ssl and www -->
</system.webServer>