14

I have a shared hosting plan with Windows Server 2008 and IIS7.5, and there is Microsoft rewriting module installed and enabled.

<rewrite>
    <rules>
        <rule name="myRule" patternSyntax="Wildcard">
            <!--Rewriting code-->
        </rule>
    </rules>
</rewrite>

So, how to redirect mydomain.example/everywhere-in-site/my-page.html to www.mydomain.example/everywhere-in-site/my-page.html with Microsoft rewriting module?

And what if I want to redirect www.mydomain.example/everywhere-in-site/my-page.html to mydomain.example/everywhere-in-site/my-page.html?

1 Answer 1

37

To remove the www from a domain and redirect to a "naked domain" you could di it like in the following code snippet:

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

And the other way around (if you prefer that) to redirect a non-www to one with www:

<rewrite>
  <rules>
    <rule name="Add WWW prefix" stopProcessing="true">
      <match url="(.*)" ignoreCase="true" />
      <conditions>
        <add input="{HTTP_HOST}" pattern="^yourdomain\.example$" />
      </conditions>
      <action type="Redirect" url="http://www.yourdomain.example/{R:0}" redirectType="Permanent" />
    </rule>
  </rules>
</rewrite>

The redirectType="Permanent" is of course optional but for SEO and most scenarios I would recommend it.

Please see also these Stack Overflow questions/answers:

1
  • 2
    This answer epitomizes how SO should be. Thanks Martin.
    – pim
    Jan 29, 2016 at 20:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.