URL 的正则表达式用可选的查询字符串参数重写

Regex for URL rewrite with optional query string parameters

我有这个重写规则:

<rule name="rentals by proptype+state+city+street test" stopProcessing="true">
  <match url=".*" />
  <conditions>
    <add input="{UNENCODED_URL}" pattern="^/([a-zA-Z0-9\-+]+)/rent/province/([a-zA-Z\-+]+)/street/([a-zA-Z0-9%\-+]+)/([0-9a-zA-Z%\-+']+)$" />
  </conditions>
  <action type="Rewrite" url="search_new.aspx?proptype={C:1}&amp;province={C:2}&amp;city={C:3}&amp;street={C:4}" appendQueryString="true" />
</rule>

我也试过:

<rule name="rentals by proptype+state+city+street test" stopProcessing="true">
  <match url=".*" />
  <conditions>
    <add input="{UNENCODED_URL}" pattern="^/([a-zA-Z0-9\-+]+)/rent/province/([a-zA-Z\-+]+)/street/([a-zA-Z0-9%\-+]+)/([0-9a-zA-Z%\-+']+)$" />
    <add input="{QUERY_STRING}" pattern=".*" />
  </conditions>
  <action type="Rewrite" url="search_new.aspx?proptype={C:1}&amp;province={C:2}&amp;city={C:3}&amp;street={C:4}" appendQueryString="true" />
</rule>

这个 URL 有效:http://www.example.com/apartment/rent/province/texas/street/houston/mystreet
但是当我添加查询字符串参数时,URL 抛出 404:http://www.example.com/apartment/rent/province/texas/street/houston/mystreet?rooms=3&pricemin=2500

我已经在这里检查过:
IIS URL Rewrite not working with query string
https://docs.microsoft.com/en-us/iis/extensions/url-rewrite-module/url-rewrite-module-configuration-reference
https://msdn.microsoft.com/en-us/library/ms972974.aspx

看来我必须使用 QUERY_STRING 服务器变量。 我实际上只想附加查询字符串参数,而不必为每个参数编写特殊的映射。我以为我可以通过 appendQueryString="true" 属性 解决这个问题,但这显然行不通。

如何确保我的重写规则也适用于查询字符串参数?

当我查看您的规则时,我了解到您正在寻找与 URL 路径 完全匹配的 (^...$)。

然而 {UNENCODED_URL} may contain query 字符串也是。因此,当 URL 包含任何查询字符串时,这违反了您的规则,即使它只是一个查询分隔符 (?).

要解决此问题,您应该查找直到查询字符串开头的匹配项,而不是直到结尾。

尝试以下规则。

<rule name="rentals by proptype+state+city+street test" stopProcessing="true">
    <match url=".*" />
    <conditions>
        <add input="{UNENCODED_URL}" pattern="^/([a-zA-Z0-9\-+]+)/rent/province/([a-zA-Z\-+]+)/street/([a-zA-Z0-9%\-+]+)/([0-9a-zA-Z%\-+']+)" />
    </conditions>
    <action type="Rewrite" url="search_new.aspx?proptype={C:1}&amp;province={C:2}&amp;city={C:3}&amp;street={C:4}" appendQueryString="true" />
</rule>