-->

IIS URL Rewrite module repeats query string

2019-07-09 03:00发布

问题:

I have this rule, to redirect all HTTP traffic to 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>

I found it on the Internet.

It works fine for simple URLs without query strings. But it duplicates query strings. For example http://example.com/path?key=value becomes https://example.com/path?key=value&key=value.

This causes problems in debugging and troubleshooting. What causes this behavior?

回答1:

Problem is that variable REQUEST_URI contains URL and query string. In your case you have two solutions:

1) Add attribute appendQueryString="false" to your action. Rule should be like that:

.

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

2) Instead REQUEST_URI you can use URL variable because this variable contains only URL without the query string. The rule should be like that:

.

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