IIS URL 重写模块查询字符串参数

Jas*_*aty 9 iis rewrite iis-7 querystring

是否可以使用URL 重写来提供比它具有的“附加查询字符串”复选框更复杂的查询字符串功能?具体来说,是否可以为某些查询字符串参数指定键并让它只附加那些名称值对。

例如,对于输入:

http://www.example.org/test?alpha=1&beta=2&gamma=3

以及查询字符串参数键列表:beta gamma

它应该输出:http : //www.example.org/redirect?beta=2&gamma=3

(请注意,输入中的查询字符串参数以任意顺序出现。)

小智 15

我的解决方案是使用条件。通过将条件与 匹配,{QUERY_STRING}您可以使用反向引用在重定向 URL 中使用它们。

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="Redirect" stopProcessing="true">
                    <match url="(.*)" />
                    <conditions trackAllCaptures="true">
                        <add input="{QUERY_STRING}" pattern="&amp;?(beta=[^&amp;]+)&amp;?" />
                        <add input="{QUERY_STRING}" pattern="&amp;?(gamma=[^&amp;]+)&amp;?" />
                        <add input="{REQUEST_URI}" pattern="^/redirect" negate="true" />
                    </conditions>
                    <action type="Redirect" url="/redirect?{C:1}&amp;{C:2}" appendQueryString="false" redirectType="Found" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>
Run Code Online (Sandbox Code Playgroud)

此解决方案唯一可能的问题可能是(取决于您想要什么),只有在查询字符串中同时存在betagamma查询字符串变量时才会发生重定向。如果不是,重定向将不会发生。

重定向规则与任何 URL ( (.*))匹配。如果需要,您可以更改它。我还添加了一个额外的条件,使规则不与重定向 URL 本身匹配,否则会导致重定向 URL 自身被重定向。