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

I would like to redirect all www traffic to non-www traffic

i have copied this into my web.config

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

per this post

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

but I got a 500 internal server error.


Solution 1:

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.

Solution 2:

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.

Solution 3:

    **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();
        }
    }