Can't change IIS response code with URL Rewrite outbound rule

Troy Hunt picture Troy Hunt · Aug 30, 2014 · Viewed 8.3k times · Source

I'm trying to set up an IIS URL Rewrite rule to match 403 responses as a result of someone attempting to browse to a directory when directory browsing is disabled. I want to then redirect them to the usual ASP.NET custom errors page I have defined for 404s.

Here's what I have at present:

<outboundRules>
  <!-- By default, browsing a directory with no default resource will return 403 -->
  <rule name="Directory browsing location">
    <match serverVariable="RESPONSE_LOCATION" pattern="(.*)" />
    <conditions>
      <add input="{RESPONSE_STATUS}" pattern="^403" />
    </conditions>
    <action type="Rewrite" value="/Error/PageNotFound?aspxerrorpath={PATH_INFO}"/>
  </rule>
  <rule name="Directory browsing status code" patternSyntax="ExactMatch">
    <match serverVariable="RESPONSE_STATUS" pattern="403" />
    <action type="Rewrite" value="302" />
  </rule>
</outboundRules>

My assumption is that it needs to be an outbound rule and that I need to rewrite both the status code and add the location response header, although the latter wouldn't exist anyway with the original 403 response.

Behaviour at the moment is... nothing. I'm still seeing 403s no matter how much tweaking I do. Any ideas out there?

Incidentally, no, there aren't any legit 403s on the site that would be swallowed as a result of this. I could also create inbound rules for each path that might result in the condition being met, but that's not very scalable.

Answer

Scott Forsyth - MVP picture Scott Forsyth - MVP · Aug 31, 2014

URL Rewrite has a handle on almost everything, but not the HTTP Status code since it's outside of the response header. So unfortunately URL Rewrite can't do anything with this, or at least not that I've ever been able to find. I've wanted to do similar things many times. Note, you can check the status with a condition using {RESPONSE_STATUS}, but you can't update it.

The response from @RyanCEI is what I would recommend. To add to that, you can use subStatusCode to scope the error to just 403.14, and for testing only, make sure to either test off-box or to set the errorMode to Custom since, by default, IIS won't show the custom error pages when testing on the local box.

Here's an example config that does both of those.

    <httpErrors errorMode="Custom">
        <error statusCode="403" subStatusCode="14" path="/errorpage.htm" responseMode="ExecuteURL" />
    </httpErrors>

After testing you can turn off the errorMode="Custom".