IIS 重写并将带空格的字符串传递给查询字符串

IIS Rewriting and Passing String With Spaces to the Querystring

我正尝试在 IIS 中使用重写规则来路由这样的请求:

domain.com/users/some%20user%20name

domain.com/cms.asp?P=users/some user name

我看到的问题是规则完全删除了空格。这是我使用的规则:

            <rule name="Rewrite Everything Else to cms.asp" stopProcessing="true">
                <match url="(.*)" />
                <conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
                <action type="Rewrite" url="cms.asp?p={R:1}" logRewrittenUrl="true" />
            </rule>

是什么导致重写期间删除空格?我该如何防止这种情况发生?

URL 中不能有 space。 http 规范声明

Spaces and control characters in URLs must be escaped for transmission in HTTP, as must other disallowed characters.

See here

如果您更喜欢可读性更高的内容,或许可以将 space 的编码规则重写为下划线或破折号。如果你知道 space 的数量,你可能可以使用

之类的东西来捕捉它
<rule name="Rewrite Everything Else to cms.asp" stopProcessing="true">
            <match url="^(.*)%20(.*)%20(.*)%20(.*)" />
            <conditions logicalGrouping="MatchAll" trackAllCaptures="false"      />
            <action type="Rewrite" url="{R:1}-{R:2}-{R:3}-{R:4}" logRewrittenUrl="true" />
        </rule>

然后重复条目:

^(.*)%20(.*)%20(.*)         replaced by:  {R:1}-{R:2}-{R:3}
^(.*)%20(.*)                replaced by:  {R:1}-{R:2}

这将处理两个和一个 space。

如果您有未知数量的 space,您可能需要实施 IIS 重写模块。

有关详细信息,请参阅 here and here