IIS重写规则 - 忽略localhost

问题描述 投票:12回答:2

我有以下规则,它可以很好地将我的www请求重定向到根目录。

但是我似乎无法将其关闭为localhost。这就是我现在拥有的:

    <rule name="CanonicalHostNameRule1">
      <match url="(.*)" />
      <conditions>
        <add input="{HTTP_HOST}" pattern="^example\.com$" negate="true" />
      </conditions>
      <action type="Redirect" url="https://example.com/{R:1}" />
    </rule>

我尝试了很多东西,包括:

    <rule name="CanonicalHostNameRule1">
      <match url="(.*)" />
      <conditions>
        <add input="{HTTP_HOST}" pattern="^localhost$" negate="true" />
        <add input="{HTTP_HOST}" pattern="^example\.com$" negate="true" />
      </conditions>
      <action type="Redirect" url="https://example.com/{R:1}" />
    </rule>

你能帮忙吗?正则表达是我的弱点唉

regex iis isapi-rewrite
2个回答
4
投票

如果使用条件仅匹配以www.开头的请求而不是在您不希望规则应用时尝试否定?这避免了否定localhost的需要,因为localhost在条件下从不匹配:

<rule name="Strip WWW" stopProcessing="true">
    <match url="(.*)" />
    <conditions>
        <add input="{HTTP_HOST}" pattern="^www\.(.*)" />
    </conditions>
    <action type="Redirect" url="https://{C:1}/{URL}" />
</rule>

但是,您尝试的规则示例(第二个代码块)也适用于在Windows 10 VM上使用IIS进行测试。我可以浏览localhost而无需重定向。也许这里还有另一个问题。


0
投票

我不会混合不同托管环境的规则; localhost(用于本地开发)和www,您的实时环境。如果将它们分开,则不必根据环境启用和禁用规则。

rules部分有一个configSource属性,您可以通过该属性指向另一个单独的文件,例如。 RewriteRules.config。这样做,web.config将如下所示。

<configuration>
    <!-- Other settings go here. -->

    <system.webServer>
        <!-- other settings go here --->

        <rewrite>
            <rules configSource="RewriteRules.config">
        </rewrite>
    </system.webServer>   
</configuration>

RewriteRules.config文件包含规则。

<rules>
    <rule name="CanonicalHostNameRule1">
        <!-- Rule details go here -->
    </rule>
</rules>

您为每个环境创建此qazxsw poi文件的单独版本,仅包含适当的规则并将其部署到相关的Web服务器。

这有很多好处。

  • 仅评估相关环境的规则,这对性能更有利。
  • 如果您有其他环境,如QA(RewriteRules.config。...)和dev(http://qa ......),它会更灵活。
  • 您不必担心(并测试)一个环境的规则是否会干扰另一个环境的规则,例如:local vs live。

http://dev文件的部署可以包含在部署自动化中。

© www.soinside.com 2019 - 2024. All rights reserved.