2

For SEO optimization reason, I get all requests to http://Example.com redirected to http://www.Example.com. The problem is that when working on local, requests to localhost get redirected as well.

I tried the suggestion in this Rewrite rule to HTTPS except when on localhost answer with no luck.

Here is my actual redirection rule located in Web.Config (hopefully it can help someone that is looking for Rewrite rule to WWW):

  <system.webServer>
    <rewrite>
      <rules>
        <rule name="redirect example.com to www.example.com">
          <match url="^(.*)" />
          <conditions>
            <add input="{HTTP_HOST}" pattern="^www\.example\.com$" negate="true" />
          </conditions>
          <action type="Redirect" url="http://www.example.com/{R:1}" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>

Any help?

Community
  • 1
  • 1
Patrick from NDepend team
  • 13,237
  • 6
  • 61
  • 92

1 Answers1

8

You can do a rule as follows

<rule name="redirect example.com to www.example.com">
   <match url=".*" />
      <conditions logicalGrouping="MatchAll">
          <add input="{HTTP_HOST}" pattern="^www.*" negate="true" />
          <add input="{HTTP_HOST}" pattern="localhost" negate="true" />
      </conditions>
      <action type="Redirect" url="http://www.example.com/{R:0}" />
   </rule>
</rules>

It combines two conditions with "MatchAll" where the first input is similar to one you already have (you can use yours if you want) and the second one is to check for localhost. Note, that you would probably need to use {R:0} and I also changed match url to .*

You can also use different web.configs (debug and release). Read more here: http://msdn.microsoft.com/en-us/library/vstudio/dd465318(v=vs.100).aspx

user2316116
  • 6,726
  • 1
  • 21
  • 35
  • I'd like to keep a single but smarter web.config, it is less error prone. Unfortunately your solution doesn't work, localhost:3064 still get redirected to www.example.com – Patrick from NDepend team Jun 03 '14 at 14:22