IIS URL的正则表达式基于URL中的参数从一个域重写到其他域

问题描述

我有一组URL,我希望根据URL中ID参数的值将其重写为其他域:

http://sub.maindomain.com/community/12345678/etc ->需要重写为:http://sub.domain1.com/etc

http://sub.maindomain.com/community/44566336/etc ->需要重写为:http://sub.domain2.com/etc

http://sub.maindomain.com/community/8181881/etc ->需要重写为:http://sub.domain3.com/etc

我发现了几篇文章,解释了如何设置重写规则,但没有一篇与上述情况相符。有任何想法吗?甚至可行吗?

解决方法

我们可以使用Path_Info服务器变量来匹配URL段中的ID参数。请参考以下代码段。

        <system.webServer>
            <rewrite>
                <rules>
                    <rule name="MyRule" stopProcessing="true">
                        <match url="(.*)" />
                        <conditions>
                            <add input="{PATH_INFO}" pattern="\/community\/([0-9]+)(.*)" />
                        </conditions>
<!--{C:1} is the value of id,{C:2} is the rest of the URL segment. it is referred by the above condition.-->
                        <action type="Redirect" url="http://{mymap:{C:1}}{C:2}" />
                    </rule>
                </rules>
          <rewriteMaps>
            <rewriteMap name="mymap" defaultValue="">
              <add key="12345678" value="www.bing.com"></add>
          <add key="44566336" value="www.microsoft.com"></add>
            </rewriteMap>
          </rewriteMaps>
            </rewrite>
    </system.webServer>

有关服务器变量的更多用法,请参见此链接。
https://docs.microsoft.com/en-us/iis/extensions/url-rewrite-module/url-rewrite-module-configuration-reference
随时让我知道是否有什么可以帮助您的。