Saturday 13 March 2010

IIS7 rewrite rule for requests from the local network

First, if you don't know about the IIS7 rewrite module, read my earlier post on it.

You back? Good.

So today I was trying to debug my web app. My web server's internal ip is 192.168.1.80, but whenever I typed this into my browser, it would send me to http://www.192.168.1.80

I discovered that this was because of one of the rules I setup earlier in the IIS7 rewrite module:

<rule name="Non www to www redirect" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTP_HOST}" pattern="^www\.yoursite\.com$" ignoreCase="true" negate="true" />
</conditions>
<action type="Redirect" url="https://www.{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" />
</rule>

Can you see why? An IP address clearly doesn't match the pattern. To solve this problem, I just added a second condition to the rule:

<rule name="Non www to www redirect" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTP_HOST}" pattern="^www\.yoursite\.com$" ignoreCase="true" negate="true" />
<add input="{HTTP_HOST}" pattern="^192\.168\.*" ignoreCase="true" negate="true" />
</conditions>
<action type="Redirect" url="https://www.{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" />
</rule>

So what is this doing? Well, it's simply saying: "If the url contains the full site name, or the request comes from inside my network, ignore this rule". Or rather, it's APPLYING the rule to anything that DOESN'T match the conditions (that's what the "negate" attribute means).

That's why I love the IIS rewrite module. I love the way you can stack conditions like this. It's nice and understandable, and easy enough to change to do whatever you want.

No comments: