IIS URL重写规则问题:含/p/且以/结尾的URL匹配异常
URL重写规则匹配问题排查与修复
我想编写一条匹配包含/p/且以/结尾的URL重写规则,现有规则能匹配https://mysite.co.il/a/p/11/,但无法匹配https://mysite.co.il/p/11/,请问这条规则存在什么问题?
现有规则代码:
<rule name="Remove trailing slash from /p/ URLs" stopProcessing="true"> <!-- Match URLs that contain /p/ and end with a trailing slash --> <match url="^(.*)/p/(.*)/$" ignoreCase="true" /> <conditions> <!-- Ensure it's not a physical file or directory --> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> </conditions> <!-- Redirect to URL without trailing slash --> <action type="Redirect" url="https://{HTTP_HOST}/{R:1}/p/{R:2}" redirectType="Permanent" /> </rule>
问题根源
你写的匹配正则^(.*)/p/(.*)/$有个硬性要求:/p/前面必须存在至少一段内容加斜杠。
- 对于
https://mysite.co.il/a/p/11/,(.*)会捕获a,满足/在/p/前的条件,所以能匹配成功; - 但对于
https://mysite.co.il/p/11/,/p/直接跟在域名后面,前面没有任何内容能符合(.*)/的要求,自然匹配失败。
修复方案
把匹配正则改成^(.*/)?p/(.*)/$,其中(.*/)?表示/p/前面的路径是可选的——既可以有前置路径,也可以没有。同时要调整重定向URL,避免{R:1}为空时出现多余的斜杠:
修正后的完整规则:
<rule name="Remove trailing slash from /p/ URLs" stopProcessing="true"> <!-- Match URLs that contain /p/ and end with a trailing slash --> <match url="^(.*/)?p/(.*)/$" ignoreCase="true" /> <conditions> <!-- Ensure it's not a physical file or directory --> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> </conditions> <!-- Redirect to URL without trailing slash --> <action type="Redirect" url="https://{HTTP_HOST}/{R:1}p/{R:2}" redirectType="Permanent" /> </rule>
内容的提问来源于stack exchange,提问作者Yosi Havia
相关产品推荐
相关产品推荐

