如何解决Web.Config Url 重写有效但重定向无效
我有以下 web.config,我在其中添加了 URL 重写和重定向规则。这是部分工作。
代码:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<caching enabled="false" />
<rewrite>
<rules>
<rule name="Rewrite to pages.asp">
<match url="^pages/([_0-9a-z-]+)" />
<action type="Rewrite" url="pages.asp?p={R:1}" />
</rule>
<rule name="Redirect from pages.asp">
<match url="^pages/([_0-9a-z-]+)" />
<action type="Redirect" url="pages/{R:1}" redirectType="Permanent" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
网址结构如下:
https://www.example.com/pages.asp?p=my-article
重写应该是这样的(并且有效):
https://www.example.com/pages/my-article/
如果我手动访问此 URL,它可以工作,但重定向部分无法正常工作。此代码有问题。
解决方法
规则都写错了,通过使用IIS重写规则管理器,我现在有一个工作代码。这可能会帮助遇到相同问题的其他人。
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<caching enabled="false" />
<rewrite>
<rules>
<rule name="RedirectPages" stopProcessing="true">
<match url="^pages\.asp$" />
<conditions>
<add input="{REQUEST_METHOD}" pattern="^POST$" negate="true" />
<add input="{QUERY_STRING}" pattern="^p=([^=&]+)$" />
</conditions>
<action type="Redirect" url="pages/{C:1}" appendQueryString="false" />
</rule>
<rule name="RewritePages" stopProcessing="true">
<match url="^pages/([^/]+)/?$" />
<conditions>
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="pages.asp?p={R:1}" />
</rule>
</rules>
<outboundRules>
<rule name="OutboundPages" preCondition="ResponseIsHtml1">
<match filterByTags="A,Form,Img" pattern="^(.*/)pages\.asp\?p=([^=&]+)$" />
<action type="Rewrite" value="{R:1}pages/{R:2}/" />
</rule>
</outboundRules>
</rewrite>
</system.webServer>
</configuration>
,
url rewrite 规则的执行顺序是从上到下,执行 Rewrite 规则后,重写的 URL 与您重定向规则中的参数不匹配,这就是重定向不起作用的原因。
更详细的错误信息,可以使用失败请求跟踪查看。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。