If you have hosted website on Windows server using IIS, you may want to enable caching in IIS to speed up your website, another issue which usually a web-developee see is to redirect non-www website to www website url, which can be done using IIS directly or using web.config, so in this article, I have provided step by step procedure to use URL Rewrite tool in IIS to redirect user from non-www to www url website OR www to non-www using web.config.

Redirect from non-www to www using IIS

Before, we begin you will have to download URL Rewrite plugin for IIS.

URL Rewrite is a tool, which enables us to create powerful rules to implement URLs that are easier for users to remember and easier for search engines to find.

Step 1: Once you have installed above tool, you can open your IIS and then navigate to website for which you want to implement url rewrite rules and select "URL Rewrite" from "IIS" tab (Middle-pane)


Step 2: Now select "Add rule(s).." from the right-pane to add a new rule


In the new dialog, select "Blank Rule"


Step 3: You will see a new dialog


Inside Inbound rules, on the "Name", enter rule name.

Then in the "Pattern" enter = (.*)

In Conditions pane, select "Match All" from dropdown and then click "Add"

In the new dialog, for Condition Input use "{HTTP_HOST}"

Check if the input string = "Matches the pattern"

In the Pattern textbox, enter your domain name as "^domain.com$" and a select the checkbox for "Ignore case". (Use above image for reference)

Step 4: Next, In the "Actions" pane


From the dropdown select "Redirect"

Then inside "Redirect URL" textbox enter "{MapProtocol:{HTTPS}}://www.domain.com/{R:1}"

Uncheck checkbox for "Append Query string"

Select "Redirect Type" -> "Permanent (301)" (Use above image for reference)

Step 5: We are done, click "Apply" to add-rule for website, from right-pane of IIS.

Web.Config will be updated and you will see below code is added after following above steps:

  <rule name="Redirect to www" stopProcessing="true">
      <match url="(.*)" />
      <conditions trackAllCaptures="false">
        <add input="{HTTP_HOST}" pattern="^domain.com$" />
      <action type="Redirect" url="{MapProtocol:{HTTPS}}://www.domain.com/{R:1}" />

the above code is placed inside "<system.webServer>" in web.Config.

Redirect from www to non-www using Web.Config

    <rule name="Redirect to non-www" stopProcessing="true">
      <match url="(.*)" negate="false"></match>
      <action type="Redirect" url="https://yourdomain.com/{R:1}"></action>
        <add input="{HTTP_HOST}" pattern="^yourdomain\.com$" negate="true"></add>

In the above code, replace "yourdomain.com" with your domain name, using the above rule, we will be redirecting users to non-www URL based website.

You may also like to read:

Enabling CORS in IIS

how to generate CSR on IIS and install SSL on IIS

Read OR Write OR Modify Web.Config file using C#