IIS URL重写模块重复查询字符串

moh*_*eli 5 url-rewrite-module

我有以下规则,将所有HTTP通信重定向到HTTPS:

<rewrite>
    <rules>
        <rule name="RedirectToHttps" enabled="true" patternSyntax="Wildcard" stopProcessing="true">
            <match url="*" negate="false" />
            <conditions logicalGrouping="MatchAny">
                <add input="{HTTPS}" pattern="off" />
            </conditions>
            <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Found" />
        </rule>
    </rules>
</rewrite>
Run Code Online (Sandbox Code Playgroud)

我在互联网上找到它。

它对于没有查询字符串的简单URL很好用。但它会重复查询字符串。例如http://example.com/path?key=value变为https://example.com/path?key=value&key=value

这会导致调试和故障排除中的问题。是什么原因导致这种现象?

Vic*_*yev 9

问题是变量REQUEST_URI包含URL和查询字符串。您的情况有两种解决方案:

1)将属性添加appendQueryString="false"到您的操作中。规则应该是这样的:

<rule name="RedirectToHttps" enabled="true" patternSyntax="Wildcard" stopProcessing="true">
    <match url="*" negate="false" />
    <conditions logicalGrouping="MatchAny">
        <add input="{HTTPS}" pattern="off" />
    </conditions>
    <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" appendQueryString="false" redirectType="Found" />
</rule>
Run Code Online (Sandbox Code Playgroud)

2)相反,REQUEST_URI您可以使用URL变量,因为此变量仅包含URL而没有查询字符串。规则应该是这样的:

<rule name="RedirectToHttps" enabled="true" patternSyntax="Wildcard" stopProcessing="true">
    <match url="*" negate="false" />
    <conditions logicalGrouping="MatchAny">
        <add input="{HTTPS}" pattern="off" />
    </conditions>
    <action type="Redirect" url="https://{HTTP_HOST}{URL}" redirectType="Found" />
</rule>
Run Code Online (Sandbox Code Playgroud)

  • 值得注意的是,我认为此页面上的官方 MS 文档是错误的: https://docs.microsoft.com/en-us/iis/web-dev-reference/server-variables 它指出 `REQUEST_URI` 是“ URI 的路径绝对部分。例如 `https://contoso.com:8042/over/there?name=ferret` 将返回 `/over/there`" 这个答案是正确的。`REQUEST_URI` 包含查询字符串。 (2认同)