Alex Rivera | Logout

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

Asked 2010-07-07T17:32:32.347
49

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\.example\.com" />
</conditions>
<action type="Redirect" url="http://example.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.

Edit
Report

1 Answer

14

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\.example\.com" />
        </conditions>
        <action type="Redirect" url="http://example.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.

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.

answered 2010-07-07T17:47:02.577

Your Answer