【问题标题】:URL Rewrite rules appear to be redirecting instead of rewritingURL 重写规则似乎是重定向而不是重写
【发布时间】:2015-07-09 02:30:00
【问题描述】:

我正在使用 IIS URL Rewrite 2.0 模块来创建一个始终指向我的应用程序最新版本的 URL。我已经配置如下:

<rule name="Latest" stopProcessing="true">
    <match url="^latest(.*)" />
    <action type="Rewrite" url="1.1{R:1}" />
</rule>

这样做的目的是,如果有东西到达/latest/*,那么所有的 URL 都会被重写为 /1.1/*。例如/latest/index.html 应该变成/1.1/index.html

这在我请求文件时起作用,例如:

/latest/index.html - works
/latest/js/app.js - works

但这不起作用:

/latest

由于index.html 是默认文档,我希望它会重写为/1.1/index.html,但实际上它似乎做了一个重定向。例如,如果我在浏览器地址栏中输入以下内容:

http://<domain>/latest

然后按 ENTER,它会变成:

http://<domain>/1.1

就像重定向一样。它仍然有效,但我不想更改 URL(因此我使用Rewrite 而不是Redirect)。知道为什么吗?我的规则有问题吗?

【问题讨论】:

    标签: iis url-rewriting url-redirection url-rewrite-module


    【解决方案1】:

    当您请求 URL /latest 时,您的规则会将其重写为 /1.1。由于/1.1 匹配现有目录而不是文件,IIS 以礼貌重定向as described here 进行响应。 IIS 使用重写后的 URL,因为它看不到原始 URL。


    建议您通过规则模拟相同的行为,而不是通过两个 URL(/latest/latest/)提供相同的内容。如果请求的 URL 是 /latest 它应该首先重定向到 /latest/ 然后重写:

    <rule name="Latest: force trailing slash" stopProcessing="true">
        <match url="^latest$" />
        <action type="Redirect" url="latest/" redirectType="Found" />
    </rule>
    <rule name="Latest: rewrite" stopProcessing="true">
        <match url="^latest/(.*)" />
        <action type="Rewrite" url="1.1/{R:1}" />
    </rule>
    

    【讨论】:

    • 是的,你是对的。我已将其与 Kev 的答案一起包含在内,现在它的行为符合我的意愿。谢谢!
    【解决方案2】:

    这可能是您遇到的问题:

    IIS generates courtesy redirect when folder without trailing slash is requested

    (虽然那篇文章是关于 IIS6,但 IIS7+ 的行为方式相同,您似乎无法禁用此行为。)

    在您现有的规则之前添加一条仅匹配 /latest 的规则(没有尾部斜杠):

    <rewrite>
        <rules>
            <rule name="Latest1" stopProcessing="true">
                <match url="^latest$" />
                <action type="Rewrite" url="1.1/" />
            </rule>
            <rule name="Latest2" stopProcessing="true">
                <match url="^latest(.*)" />
                <action type="Rewrite" url="1.1{R:1}" />
            </rule>
        </rules>
    </rewrite>
    

    可能还有一种更优雅的方式,就是按照锡上所说的那样做。

    您可能需要重新加载页面,因为您的浏览器可能会缓存重定向,您始终可以在“隐身模式”下进行测试,该模式永远不会在会话之间保存永久重定向。

    【讨论】:

    • 谢谢,它似乎在一定程度上起作用,除了 index.html 中引用的所有资源似乎是从错误的 URL 加载的。例如,如果我转到 /latest,那么
    • 忽略之前的评论 - 我认为 Salman A 也解释并解决了这个问题。
    猜你喜欢
    • 1970-01-01
    • 2018-03-11
    • 2022-06-10
    • 1970-01-01
    • 1970-01-01
    • 2019-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多