Ayo Adesina
Ayo Adesina

Reputation: 2415

IIS URL Rewriting rule - exclude ALL files and a specific path

I want to create a URL rewrite rule that adds a / on URLs that don't have one so for example:

www.domain.com/news/latest will get redirected to www.domain.com/news/latest/

The rule below does exactly that, but the problem I am having is two fold:

  1. This rewrite rule is getting applied to things like image files. So For example domain.com/globalassets/icons/image.svg gets changed to domain.com/globalassets/icons/image.svg/ causing a 404 its not happening with CSS files which is strange, maybe because I am adding them using the RegisterBundles method in MVC?

  2. This is a ASP.NET MVC based website using a CMS (episerver) so I want to ignore any redirects in the Admin area so I added a second rule, but again its doing this to the CSS and images breaking the admin area.

This is what I have got so far, can anyone help me get this rule working correctly?

<rewrite>
    <rules>

      <rule name="Exclude Slash Episerver " stopProcessing="true">
        <match url="^episerver/" />
        <action type="None" />
      </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>

    </rules>
</rewrite>

Upvotes: 0

Views: 3143

Answers (1)

NightOwl888
NightOwl888

Reputation: 56869

Common SEO rewrite rules for IIS such as this one are documented here.

In particular, with the Trailing Slash rule you are missing the logicalGrouping="MatchAll" attribute:

Conditions are defined within a <conditions> collection of a rewrite rule. This collection has an attribute called logicalGrouping that controls how conditions are evaluated. If a rule has conditions, then the rule action is performed only if rule pattern is matched and:

  • All conditions were evaluated as true, provided that logicalGrouping="MatchAll" was used.
  • At least one of the conditions was evaluated as true, provided that logicalGrouping="MatchAny" was used.

Without this setting, it is adding a trailing slash to your file names because it is matching when any of your negated rules match rather than all of them.


The entire Trailing Slash rule from the above link is:

<rule name="Trailing Slash" stopProcessing="true"> 
    <match url="(.*[^/])$" /> 
    <conditions logicalGrouping="MatchAll" trackAllCaptures="false"> 
        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> 
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> 
        <add input="{URL}" pattern="WebResource.axd" negate="true" /> 
    </conditions> 
    <action type="Redirect" url="{R:1}/" /> 
</rule>

Upvotes: 1

Related Questions