【问题标题】:Rewrite rule to HTTPS except when on localhost将规则重写为 HTTPS,除非在本地主机上
【发布时间】:2014-01-23 17:27:30
【问题描述】:

我正在使用答案 given here 作为尝试将重写规则添加到我的 web.config 文件的基础。我希望它匹配任何未在 localhost 上运行的 url 以强制使用 https。

这是我现在拥有的:

<system.webServer>
  <rewrite> <!-- force https - https://stackoverflow.com/a/15119044/51 -->
    <rules>
      <rule name="Redirect HTTP to HTTPS" stopProcessing="true">
        <match url="^((?!localhost).)*$"/>
        <conditions>
          <add input="{HTTPS}" pattern="^OFF$"/>
        </conditions>
        <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="SeeOther"/>
      </rule>
    </rules>
  </rewrite>
</system.webServer>

我正在尝试使用negative lookaround,以便仅匹配不包含“localhost”的 url。但这不起作用。

那么应该如何设置这个规则才能只重写非本地 url 的呢?

【问题讨论】:

    标签: regex asp.net-mvc url-rewriting web-config


    【解决方案1】:

    试试这个条件:

    <system.webServer>
      <rewrite>
        <rules>
          <rule name="Redirect HTTP to HTTPS" stopProcessing="true">
            <match url="^(.*)$"/>
            <conditions>
              <add input="{HTTPS}" pattern="^OFF$"/>
              <add input="{HTTP_HOST}" matchType="Pattern" pattern="^localhost$" negate="true" /> 
            </conditions>
            <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="SeeOther"/>
          </rule>
        </rules>
      </rewrite>
    </system.webServer>
    

    localhost 模式使用negate 条件应该可以解决问题。

    【讨论】:

    • 结果为@​​987654325@
    • 同样的错误。我怀疑它可能与引用分组的操作有关 - {R:1} - 它不再包含在匹配的正则表达式中。
    • 是的,确实如此,让我也为你推荐一些东西。
    • 如果您使用自定义端口(如 localhost:6002),请查看@firstTimeCaller 答案:stackoverflow.com/a/23554829/237858
    【解决方案2】:

    添加到 anubhava 的 answer,您可以将 localhost 的 add 元素替换为以下 2 个条目,以使用可选端口满足 localhost 和 127.0.0.1,例如 localhost:59400,这是通过 Visual Studio 和 IIS 调试时的情况

    <add input="{HTTP_HOST}" matchType="Pattern" pattern="^localhost(:\d+)?$" negate="true" />
    <add input="{HTTP_HOST}" matchType="Pattern" pattern="^127\.0\.0\.1(:\d+)?$" negate="true" />    
    

    使用原始答案,localhost:123 将被重定向到 https,这可能是不可取的。

    【讨论】:

    • 这个对我有用。 anubhava 的回答不考虑 localhost:XXXX 情况(端口)
    • 这对我有用,除非我导航到根目录(“/”)。然后由于某种原因,它将我重定向到 HTTPS。
    • @MikeW 我在导航到 root 时遇到了同样的问题。不知道如何解决。
    • 这是我的全部规则 - 似乎正在工作...
    • @drewid 我在访问 root 时遇到了同样的问题,并通过在条件元素上设置以下属性来解决它:logicalGrouping="MatchAll"。所以现在我的元素是:
    【解决方案3】:

    更新正则表达式,这对我有用,带有自定义端口

    <add input="{HTTPS}" pattern="off" ignoreCase="true" />
    <add input="{HTTP_HOST}" matchType="Pattern" pattern="(localhost)(:\d+)" negate="true" />
    <add input="{HTTP_HOST}" matchType="Pattern" pattern="(127.0.0.1)(:\d+)" negate="true" />
    

    【讨论】:

    • 吹毛求疵:点在 POSIX 正则表达式中有特殊含义,需要转义。所以 127.0.0.1 应该是 127\.0\.0\.1
    猜你喜欢
    • 2014-07-23
    • 2017-11-24
    • 2014-11-30
    • 1970-01-01
    • 1970-01-01
    • 2018-05-06
    • 2016-10-07
    • 2011-09-18
    • 2016-01-07
    相关资源
    最近更新 更多