asp.net - iis url 重写中奇怪的正则表达式错误

标签 asp.net regex url-rewriting web-config

这是我的模式:

^(\w{2}-\w{2})/questions(?:/(\w+))?(?:/(\d+))?(?:/.*?)?$

这些是我正在测试的:

en-us/questions/ask
en-us/questions/newest/15
en-us/questions/12/just-a-text-to-be-ignored

它运行完美,这是演示:

https://regex101.com/r/yC3tI8/1

但重写规则如下:

<rule name="en-us questions" enabled="true" stopProcessing="true">
  <match url="^(\w{2}-\w{2})/questions(?:/(\w+))?(?:/(\d+))?(?:/.*?)?$" />
  <action type="Rewrite" url="/questions.aspx?lang={R:1}&amp;tab={R:2}&amp;pid={R:3}" />
</rule>  

当我将链接en-us/questions/newest重定向到:/questions.aspx?lang=en-us&tab=&pid=

这有什么问题吗?现在大约有 5 个小时,我只是在回顾同样的事情

最佳答案

由于您有三种不同的可能的网址结尾,它们最终会影响重写网址的结果,因此您可以设置一个包含所有内容的规则,希望匹配您想要的所有内容,或者您​​可以设置三个规则来相应地处理每个:

一条规则:

^(\w{2}-\w{2})/questions/(\w+)/?(\d+)?.*$

https://regex101.com/r/dN8bM9/1 - tries to handle all cases

<rule name="en-us questions" enabled="true" stopProcessing="true">
  <match url="^(\w{2}-\w{2})/questions/(\w+)/?(\d+)?.*$" />
  <action type="Rewrite" url="/questions.aspx?lang={R:1}&amp;tab={R:2}&amp;pid={R:3}" />
</rule> 

* 注意:原始模式未能捕获第二组的一个可能原因是包含 (?:) - 这意味着匹配但不捕获;忽略这一点可能会解决那里的大部分问题。

三个规则:

^(\w{2}-\w{2})/questions/(\w+)$

https://regex101.com/r/lI8bQ1/1 - en-us/questions/[single word]

^(\w{2}-\w{2})/questions/(\d+)/.*$

https://regex101.com/r/hV5fK3/1 - en-us/questions/[digits]/discard

^(\w{2}-\w{2})/questions/(\w+)/(\d+)$

https://regex101.com/r/kO0dJ0/1 - en-us/questions/[single word]/[digits]

将它们全部放在一个规则集中:

<rule name="en-us questions case one" enabled="true" stopProcessing="true">
  <match url="^(\w{2}-\w{2})/questions/(\w+)$" />
  <action type="Rewrite" url="/questions.aspx?lang={R:1}&amp;tab={R:2}" />
</rule>  
<rule name="en-us questions case two" enabled="true" stopProcessing="true">
  <match url="^(\w{2}-\w{2})/questions/(\d+)/.*$" />
  <action type="Rewrite" url="/questions.aspx?lang={R:1}&amp;tab={R:2}" />
</rule>  
<rule name="en-us questions case three" enabled="true" stopProcessing="true">
  <match url="^(\w{2}-\w{2})/questions/(\w+)/(\d+)$" />
  <action type="Rewrite" url="/questions.aspx?lang={R:1}&amp;tab={R:2}&amp;pid={R:3}" />
</rule>

* 注意:您可能需要以某种方式调整它,但它应该让您了解如何适应三种不同的变体(正如您似乎拥有的那样)来重写您的网址。

关于asp.net - iis url 重写中奇怪的正则表达式错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31222246/

相关文章:

regex - 匹配 "select...from...where"sql查询的正则表达式

正则表达式匹配除特定路径之外的所有 https URL

wordpress - 在 WordPress PHP 中将长域 URL 重写为短域 URL

c# - 为移动浏览器设计网页的技巧?

asp.net - MySQL 的 ASPNETDB.mdf

c# - 正则表达式限制电子邮件地址开头的特殊字符

php - 从子目录飞行 PHP 路由

jquery - 如何在asp.net中创建一次性通知系统

c# - 静态属性最终会出现在 gen2 中吗?

html - 如何删除 beautifulsoup 中特定模式内的任何 html 标签