Regex for URL rewrite with optional query string parameters

断了今生、忘了曾经 提交于 2020-01-04 10:43:08

问题


I have this rewrite 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%\-+']+)$" />
  </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>

I also tried:

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

This URL works: http://www.example.com/apartment/rent/province/texas/street/houston/mystreet
But when I add query string parameters, the URL throws a 404: http://www.example.com/apartment/rent/province/texas/street/houston/mystreet?rooms=3&pricemin=2500

I already checked here:
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

It seems I have to use a QUERY_STRING server variable. I actually just want to append the query string parameters, without having to write a special mapping for each parameter. I thought I could solve this through the appendQueryString="true" property, but that apparently doesn't work.

How can I make sure my rewrite rule works also with query string parameters?


回答1:


When I look at your rule, I understand that you are looking for a complete match (^...$) with URL Path.

However {UNENCODED_URL} may contain query strings too. So this breaks your rule when the URL contains any query string, even if it's just a query separator (?).

To fix this you should look for a match until the beginning of the query string instead, not till the end.

Try the following 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%\-+']+)" />
    </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>


来源:https://stackoverflow.com/questions/46229792/regex-for-url-rewrite-with-optional-query-string-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!