【问题标题】:Regex for URL rewrite with optional query string parameters使用可选查询字符串参数重写 URL 的正则表达式
【发布时间】:2018-02-24 01:39:07
【问题描述】:

我有这个重写规则:

<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" 属性解决这个问题,但这显然行不通。

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

【问题讨论】:

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


    【解决方案1】:

    当我查看您的规则时,我了解到您正在寻找与 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>
    

    【讨论】:

    • Jup,就是这样。谢谢,将在 23 小时内奖励赏金 :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-21
    • 1970-01-01
    • 1970-01-01
    • 2014-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多