IIS 重写规则,随机概率为 50/50



我想创建两个 IIS 重写规则,以便规则 A 将在 50% 的请求上运行,B 将在另外 50% 的请求上运行。IIS 重写模块 AFAIK 中没有内置的随机属性。我想在不开发自己的重写模块扩展的情况下实现它。

我更喜欢随机尽可能"真实"(当然,伪随机算法可以是随机的)。

我想到了两种可能性:

  1. 获取当前时间戳并使用时间戳的奇偶校验。是否有这样的服务器变量可用?我没有找到它。
  2. 使用客户端 IP 的最后一部分 (REMOTE_ADDR) 的奇偶校验。

这些选项之一是否可行?如何使用重写规则实现它们?有没有更好的解决方案?

看起来REMOTE_ADDR选项是可行的:

<!-- 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]$"/>

您可以通过更改模式轻松将其设置为 30/70 或 10/90。

以随机方式设置 Cookie 的示例配置:

<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>

最新更新