将规则重写为HTTPS,但在localhost上除外

Yaa*_*lis 33 regex asp.net-mvc web-config url-rewriting

我使用这里给出的答案作为尝试向我的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>
Run Code Online (Sandbox Code Playgroud)

我试图使用负面的环视,以便只匹配url中不包含"localhost"的url.但这不起作用.

那么如何设置此规则才能只重写非localhost网址呢?

anu*_*ava 51

试试这个条件:

<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>
Run Code Online (Sandbox Code Playgroud)

使用negate针对localhost模式的条件应该可以解决问题.

  • 如果您使用自定义端口(如localhost:6002),请查看@firstTimeCaller答案:http://stackoverflow.com/a/23554829/237858 (5认同)

Sam*_*ppe 45

添加到anubhava的答案,您可以使用以下2个条目替换localhost的add元素以满足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" />    
Run Code Online (Sandbox Code Playgroud)

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

  • 这对我有用,除非我导航到root("/").然后由于某种原因它将我重定向到HTTPS. (3认同)
  • 这个对我有用。anubhava的答案不考虑 localhost:XXXX 情况(端口) (2认同)
  • 这是我的整个规则 - 似乎有效...... &lt;rule name="HTTP to HTTPS Redirect" enabled="true" stopProcessing="true"&gt; &lt;match url="(.*)"/&gt; &lt;conditions&gt; &lt;添加 input="{HTTP_HOST}" matchType="Pattern" pattern="^localhost(:\d+)?$" negate="true" /&gt; &lt;add input="{HTTP_HOST}" matchType="Pattern" pattern=" ^127\.0\.0\.1(:\d+)?$" negate="true" /&gt; &lt;add input="{SERVER_PORT_SECURE}" pattern="^0$" /&gt; &lt;/conditions&gt; &lt;action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" /&gt; &lt;/rule&gt; (2认同)