首页 > 解决方案 > 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>

URL结构是这样的:

https://www.example.com/pages.asp?p=my-article

重写应该是这样的(并且有效):

https://www.example.com/pages/my-article/

如果我手动访问此 URL,它可以工作,但重定向部分无法正常工作。这段代码有问题。

标签: asp.netweb-configiis-10

解决方案


规则都写错了,通过使用 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=([^=&amp;]+)$" />
                    </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=([^=&amp;]+)$" />
                    <action type="Rewrite" value="{R:1}pages/{R:2}/" />
                </rule>
                
            </outboundRules>
          
          
        </rewrite>
            
    </system.webServer>
</configuration>

推荐阅读