这是我的模式:
^(\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}&tab={R:2}&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}&tab={R:2}&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}&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}&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}&tab={R:2}&pid={R:3}" />
</rule>
* 注意:您可能需要以某种方式调整它,但它应该让您了解如何适应三种不同的变体(正如您似乎拥有的那样)来重写您的网址。
关于asp.net - iis url 重写中奇怪的正则表达式错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31222246/