Web.Config 使用 mysql 数据库中的名称重写 URL



我有一个Web.config文件,我用它来以友好的方式重写url,如下所示:

<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                // rewrites here
                <rule name="articles" stopProcessing="true">
                    <match url="^article/([0-9]+)/?$" ignoreCase="true" />
                    <conditions logicalGrouping="MatchAll">
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="/article.asp?id={R:1}" appendQueryString="true" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>

但是我需要显示 mywebsite.com/article/1/数据库中的文章名称,例如 mywebsite.com/title-article/。 我已经做了很好的研究,但我没有找到任何真正解释如何做到这一点的东西。

我认为web.config不可能做到这一点,因为web.config无法查询数据库。 您所能做的就是为文章表中的每个页面创建一个单独的重写规则。

您的另一个选项,也是在 IIS URL 重写模块出现之前使用更多的选项是创建自定义 404 页面并将逻辑放入该页面中。

在配置文件的 system.webServer 部分中,添加以下内容:

<httpErrors errorMode="Custom">
<remove statusCode="404" subStatusCode="-1" />
<error statusCode="404" prefixLanguageFilePath="" path="/404.asp" responseMode="ExecuteURL" />
</httpErrors>

在 404 页面上,您可以检索将用户带到该页面的网址

Request.ServerVariables("query_string")

然后,您可以使用 VBScript 获取所需的 URL 部分,并在数据库查询中使用它。 在您的示例中使用 Url 模式,我建议

Dim TitleArticle
TitleArticle = Replace(Request.ServerVariables("query_string"),"404;http://mywebsite.com/","") 

然后,您可以在数据库查询中使用TitleArticle来查找所需的页面,并Server.Transfer将用户带到那里,同时保留地址栏中的友好 URL。 我建议在测试时使用Response.Write TitleArticle,以确保向数据库发送正确的值。

显然,这一切都需要在条件语句中,Else条件是显示标准的 404 消息

最新更新