Search code examples
regexurl-rewritingurl-rewrite-moduleiis-10

How to configure an IIS re-write rule with specific pattern?


I am trying to create a URL rewrite rule to send any url that ends with a specific 2-character string (case-insensitive) to a different url.

For example, I want these to match:

http://www.foo.com/mn  
http://www.foodev.com/mn  
http://www.foo.com/MN  
http://www.foodev.com/MN  

But these to fail:

http://www.foo.com/la/mn  
http://www.foo.com/la/di/da/mn  
http://www.foodev.com/la/mn  
http://www.foodev.com/la/di/da/mn

I set up the following rule:

    <rule name="Redirect MN" enabled="true" stopProcessing="true">
      <match url="(.*)" ignoreCase="true"  />
    <conditions>
        <add input="{PATH_INFO}" pattern="/\/mn$/gmi" />
     </conditions>        
      <action type="Redirect" url="https//www.foo.com/mn" appendQueryString="false" redirectType="Permanent" />
    </rule> 

Where I'm using the {PATH_INFO} value with the pattern /\/mn$/gmi which seems like it should match: https://regex101.com/r/ql2USW/1/

When I view the event in the FREBUI viewer, I see the expanded input and the pattern (which appear to be correct), but it does not succeed.

Input {PATH_INFO} 
ExpandedInput /MN 
MatchType Pattern 
Pattern /\/mn$/gmi 
Negate false 
Succeeded false 

How should I change the configuration of this rule?

Screenshot of the FREBUI

Microsoft-IIS/10.0


Solution

  • Maybe, we could solve this problem. Let's start with a simple expression to pass our desired URLs and fail the undesired ones. Later, if we wish, we can restrict it with additional boundaries.

    Here, this expression would likely match the desired URLs by simply removing the $ char:

    \.com\/mn
    

    And I'm hoping that the problem might be solved here.

    Demo

    We could though continue adding boundaries such as, one in the left of .com:

    .+\.com\/mn
    

    Demo

    Or similar to your original version, we can add start and end boundaries:

    ^.+\.com\/mn$
    

    Demo

    Then, our setup might likely look like:

    <rule name="Redirect MN" enabled="true" stopProcessing="true">
        <match url="(.*)" ignoreCase="true"  />
        <conditions>
            <add input="{PATH_INFO}" pattern="\.com\/mn/gmi" />
        </conditions>        
        <action type="Redirect" url="https//www.foo.com/mn" appendQueryString="false" redirectType="Permanent" />
    </rule> 
    

    Or any other pattern that we wish to change would likely goes here:

    pattern="\.com\/mn/gmi"
    

    enter image description here

    RegEx

    If this expression wasn't desired, it can be modified or changed in regex101.com.

    RegEx Circuit

    jex.im also helps to visualize the expressions.

    enter image description here