【问题标题】:Conditional https redirect on IIS 7IIS 7 上的条件 https 重定向
【发布时间】:2012-12-14 17:12:04
【问题描述】:

我在网站上有以下规则将 http 重定向到 https。我们刚刚发现,我们的应用程序仅使用 api 的 http 提交。在我们得到更新之前,我需要站点忽略对 /api 文件夹的调用,只重定向其他所有内容。我敢肯定有办法说如果 URL 不包含 /api/ 然后重定向。

<rewrite>
  <rules>
    <rule name="HTTP to HTTPS redirect" stopProcessing="true">
      <match url="(.*)" />
      <conditions>
        <add input="{HTTPS}" pattern="off" ignoreCase="true" />
      </conditions>
      <action type="Redirect" redirectType="Found" url="https://{HTTP_HOST}/{R:1}" />
    </rule>
  </rules>
</rewrite>

【问题讨论】:

    标签: asp.net asp.net-mvc iis iis-7 http-redirect


    【解决方案1】:

    添加类似于&lt;add input="{R:0}" pattern="/api(/|$)(.*)" negate="true" /&gt; 的条目,使整个文件为:

    <rewrite>
      <rules>
        <rule name="HTTP to HTTPS redirect" stopProcessing="true">
          <match url="(.*)" />
          <conditions>
            <add input="{R:0}" pattern="/api(/|$)(.*)" negate="true" />
            <add input="{HTTPS}" pattern="off" ignoreCase="true" />
          </conditions>
          <action type="Redirect" redirectType="Found" url="https://{HTTP_HOST}/{R:1}" />
        </rule>
      </rules>
    </rewrite>
    

    示例网址:http://site.com/api/function

    因此,如果站点后的 URL 与以下任何一个匹配,它将停止处理(因此不会将用户推送到 https)

    • /api
    • /api/anything
    • 任何https URL

    我们在反向代理后面的 IIS 中运行大型应用程序时遇到了同样的事情。 IIS 的 URL 重写插件(您似乎正在使用)有点麻烦,但它确实做得很好并且可以容忍 MVC 框架。

    正如您所提到的,简单地将重写块放在 API 目录中是行不通的,因为 MVC 没有目录。您会认为 MS 对此会有更好的解决方案——但他们没有。这让事情变得更具挑战性。

    【讨论】:

      【解决方案2】:

      如果您将单独的 Web.config 文件放在 /api 应用程序或目录中,您可以覆盖适用于整个站点的任何规则。

      查看本文中的提示 #1,如果您有时间阅读所有内容:

      http://weblogs.asp.net/jgalloway/archive/2012/01/17/10-things-asp-net-developers-should-know-about-web-config-inheritance-and-overrides.aspx

      John Galloway 的博客是 IIS 和 ASP.NET 的绝佳资源。

      【讨论】:

      • 除了这是一个 MVC 应用程序外,它还可以工作,所以技术上没有 API 目录。
      • 我明白了!作为快速修复,您可以在“匹配 url”字段中使用正则表达式并编写特定于 API 的规则。
      • 我就是这么想的,就是不知道正则表达式部分怎么写。
      • 但我希望其他人有一个更优雅、更长期的 MVC 解决方案;)
      猜你喜欢
      • 1970-01-01
      • 2011-11-10
      • 2018-03-21
      • 2019-08-17
      • 2015-12-08
      • 1970-01-01
      • 1970-01-01
      • 2011-06-24
      • 2017-11-01
      相关资源
      最近更新 更多