IIS URL Rewrite-Rules Skipping Files-types

If you need to put in a rule for the IIS URL Rewrite Module, but need the rule to skip some file-endings and/or targets that are directories or actual files on disk, this is the post for you.

IIS Welcome

Following some SEO best-practices that tells us to use trailing slashes on our URLs I used the IIS Manager and added the IIS URL Rewrite-module's built-in rule "Append or remove the trailing slash symbol", which creates the following rule:

 <rule name="Add trailing slash" stopProcessing="true">
  <match url="(.*[^/])$" />
  <conditions>
    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
    <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
  </conditions>
  <action type="Redirect" redirectType="Permanent" url="{R:1}/" />
</rule>

This rule takes into account and doesn't apply the rule to files and directories that exists on disk. But there is a big problem with this generic rule.

If you are dynamically serving up files with extensions, then an URL like:

http://website.com/about.html

will become:

http://website.com/about.html/

Adding conditions for specific file-endings

To solve this you can add conditions for certain file-endings, like .html and .aspx:

<conditions>
  <!-- ... -->
  <add input="{REQUEST_FILENAME}" pattern="(.*?)\.html$" negate="true" />
  <add input="{REQUEST_FILENAME}" pattern="(.*?)\.aspx$" negate="true" />
</conditions>

Since the rules above already don't apply for files physically on disk, you don't need to add file-endings like .css, .png or .js.

Update: Match ANY file-ending

If you want to match just any file-ending at all, you use the following pattern:

<conditions>
  <!-- ... -->
  <add input="{URL}" pattern=".*/[^.]*\.[\d\w]+$" negate="true" />
</conditions>
Comments