Question

I've got a site with a bunch of redirects specified in a <redirectMap> and a few over-arching rules but my knowledge of IIS Rewrite is not all that and it's not working as intended.

The logic I need is:

  1. First, strip any trailing slash from the URL.
  2. Lowercase the URL
  3. Match the URL against the redirectMap and 301 if a match was found.
  4. If no match for #3, check the current re-written URL against the original URL and 301 if they are different (enforces lowercase on already valid URLs).

I only want to perform a single redirect where possible, therefore #1 and #2 should rewrite the URL and pass it on to the next rule. They should not issue 301s of their own.

How do I match against the original URL? My #4 rule is just not right.

Here's what I've got so far. The rewriteMap is not shown for brevity:

<rules>
  <rule name="Strip trailing slash" stopProcessing="false">
    <match url="(.*)/$" />
    <conditions>
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true"/>
        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true"/>
    </conditions>
    <action type="Rewrite" url="{R:1}" />
  </rule>

  <rule name="Convert to lower case" stopProcessing="true">
    <match url=".*[A-Z].*" ignoreCase="false" />
    <action type="Rewrite" url="{ToLower:{R:0}}" />
  </rule>

  <!-- Rule referencing rewrite map -->
  <rule name="Redirect Rule" stopProcessing="true">
    <match url=".*" />
    <conditions>
       <add input="{StaticRedirects:{REQUEST_URI}}" pattern="(.+)" />
    </conditions>
    <action type="Redirect" url="{C:1}" appendQueryString="False"
            redirectType="Permanent" />
  </rule>

  <!-- Redirect if the URL has been transformed -->
  <rule name="Redirect If Transformed" stopProcessing="true">
    <!-- This rule checks if the current URL has changed from the original URL
         by being lowercased or having the trailing slash removed. 
         If so, it 301s the request to the new URL.
    -->
    <match url=".*" />
    <conditions>
      <add input="{REQUEST_URI}" pattern="{HTTP_X_ORIGINAL_URL}" />
    </conditions>
    <action type="Redirect" url="{C:1}" appendQueryString="False"
            redirectType="Permanent" />
  </rule>
</rules>

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top