Search code examples
regexiis-7.5url-rewrite-module

Regex URL rewriting for custom login page


I'm implementing a custom login page for a multitenant portal where each client gets a different login page styled according to their stored settings.
To achieve this I am using IIS 7.5 with the URL Rewriting module.
My idea is to capture requests for "http://portal.com/client1/" and rewrite them into "http://portal.com/login.aspx?client=client1".

What I'm struggling with is the regex expression to match the URL and extract the "client1" bit out.

EXAMPLES:
"http://portal.com/pepsi" = "http://portal.com/login.aspx?client=pepsi"
"http://portal.com/fedex" = "http://portal.com/login.aspx?client=fedex"
"http://portal.com/northwind" = "http://portal.com/login.aspx?client=northwind"
"http://portal.com/microsoft/" = "http://portal.com/login.aspx?client=microsoft"

So the match should be found if the requested URL contains a single word after the first "/" and work whether there is a trailing "/" or not.

"http://portal.com/clients/home.aspx" would be ignored by the rule.
"http://portal.com/clients/catalog" would be ignored by the rule.
"http://portal.com/products.aspx" would be ignored by the rule.

Solution

  • Assuming:

    • That the parameter name is always client
    • and that you don't care about what is after /client1/ then you can use this simple pattern to capture that portion of the URL and then repeat it as a parameter

    here:

    <rewrite>  
      <rules>
         <rule name="client1 rewrite">
          <match url="^([^/.]*)[/]*$" />
          <action type="rewrite" url="login.aspx?client={R:1}"/>
        </rule>
      </rules>
    </rewrite>
    

    Fiddle

    This works because in all of the ignore list there is a slash in the "middle", but the slash is optional at ending of the "filter" list. So {R:1} will contain everything up to the first slash or end of url if there is no slash.