编写包含路径的 IIS 重写规则

问题描述 投票:0回答:1

我们网站中的所有网页都位于网站根目录下的

/pub/src/
目录下。我需要一个重写规则来保留 URL,但打开
/pub/src/
目录中的相应文件。例如:

  1. sitename.com/index.asp -> 打开 -> sitename.com/pub/src/index.asp
  2. sitename.com/login/index.asp -> 打开 -> sitename.com/pub/src/login/index.asp
  3. (默认文档也应该有效)sitename.com -> 打开 -> sitename.com/pub/src/index.asp

这是我到目前为止所拥有的:

<rule name="RewriteASPFiles" stopProcessing="true">
    <match url="^(.+\.asp)$" />
    <conditions>
        <add input="{REQUEST_FILENAME}" matchType="IsFile" />
    </conditions>
    <action type="Rewrite" url="/pub/src/{R:1}" />
</rule>

正则表达式捕获文件夹路径和文件名。但是,当

/index.asp
正确打开
/pub/src/index.asp
时,
/login/index.asp
给出 404 - 文件未找到。该规则也不会捕获默认文档。为了让我上面的第二个和第三个例子也能正常工作,还缺少什么?

regex iis web-config
1个回答
0
投票

我测试了你的重写规则,结果如下:

1./index.asp可以正确打开/pub/src/index.asp

2./login/index.asp 给出 HTTP 错误 404.0 - 未找到。

然后我启用了失败请求跟踪并得到了以下跟踪日志。

可以看到规则中的这个条件没有匹配成功。它检查请求的文件是否存在,只有请求的文件存在才认为满足条件。

<add input="{REQUEST_FILENAME}" matchType="IsFile" />

您的请求URL为/login/index.asp,该文件对应的物理路径(C:\inetpub\wwwroot\login\index.asp)不存在,所以不满足。

如果删除规则中的条件,则可以满足第一个和第二个示例。

3.对于第三个示例,sitename.com -> 打开 -> sitename.com/pub/src/index.asp。它与您现有的规则不匹配,因此您需要创建另一个规则。

请尝试以下修改后的重写规则,这将使您的所有三个示例都有效。

<rewrite>
  <rules>
    <!-- Rule 1: Match URL path ending with .asp -->
    <rule name="RewriteASPFiles" stopProcessing="true">
      <match url="^(.+\.asp)$" />
      <action type="Rewrite" url="/pub/src/{R:1}" />
    </rule>

    <!-- Rule 2: Match empty path -->
    <rule name="MatchEmptyPath" stopProcessing="true">
      <match url="^$" />
      <action type="Rewrite" url="/pub/src/{R:0}" />
    </rule>
  </rules>
</rewrite>
© www.soinside.com 2019 - 2024. All rights reserved.