2

I want to create two IIS rewrite rules, such that rule A will run on 50% of the requests, and B on the other 50%. There is no builtin random property in the IIS rewrite module AFAIK. I want to achieve it without developing my own rewrite module extension.

I prefer the random to be as "true" as possible (as far as pseudo-random algorithms can be random of course).

I thought about two possibilities:

  1. Get the current timestamp and use the parity of the timestamp. Is there such server variable available? I didn't find it.
  2. Use the parity of the last part of the client IP (REMOTE_ADDR).

Are one of these options feasible? How can I implement them with rewrite rules? Is there a better solution?

iTayb
  • 12,373
  • 24
  • 81
  • 135

1 Answers1

1

It looks like the REMOTE_ADDR option is feasible:

<!-- Condition for even IPs (50% connections) -->
<add input="{REMOTE_ADDR}" pattern=".+[02468]$"/>

<!-- Condition for odd IPs (the other 50% connections): -->
<add input="{REMOTE_ADDR}" pattern=".+[13579]$"/>

You can easily make it 30/70 or 10/90 by changing the pattern.

Example configuration for setting a cookie in a random manner:

<rewrite>
    <outboundRules>
        <rule name="set new=1 on half the requests" preCondition="new-cookie-is-not-set">
            <match pattern=".*" serverVariable="RESPONSE_Set_Cookie"/>
            <conditions trackAllCaptures="false">
                <add input="{REMOTE_ADDR}" pattern=".+[02468]$"/>
            </conditions>
            <action type="Rewrite" value="new=1; Expires=Fri, 26 Apr 2020 00:00:00 GMT; HttpOnly"/>
        </rule>
        <rule name="set new=0 on the other half" preCondition="new-cookie-is-not-set">
            <match pattern=".*" serverVariable="RESPONSE_Set_Cookie"/>
            <conditions trackAllCaptures="false">
                <add input="{REMOTE_ADDR}" pattern=".+[13579]$"/>
            </conditions>
            <action type="Rewrite" value="new=0; Expires=Fri, 26 Apr 2020 00:00:00 GMT; HttpOnly"/>
        </rule>
        <preConditions>
            <preCondition name="new-cookie-is-not-set">
                <add input="{HTTP_COOKIE}" negate="true" pattern="new=[01]"/>
            </preCondition>
        </preConditions>
    </outboundRules>
</rewrite>
iTayb
  • 12,373
  • 24
  • 81
  • 135