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

时间:2017-09-14 23:59:57

标签: asp.net regex url-rewriting query-string server-variables

我有这个重写规则:

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

此网址有效: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"属性解决这个问题,但这显然不起作用。

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

1 个答案:

答案 0 :(得分:1)

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

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