【问题标题】:IIS Rewrite rule - ignore for localhostIIS 重写规则 - 忽略 localhost
【发布时间】:2018-11-13 11:36:59
【问题描述】:

我有以下规则,可以很好地将我的 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>

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

【问题讨论】:

  • 检查this post。
  • @WiktorStribiżew 我尝试添加一个条件 但这不起作用?我做错了什么?
  • 也许你需要使用&lt;rule name="CanonicalHostNameRule1" stopProcessing="true"&gt;?
  • 不,不幸的是它不起作用......
  • 您是否尝试过将localhost 作为您的模式

标签: regex iis isapi-rewrite


【解决方案1】:

如何使用条件仅匹配以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 而无需重定向。也许这里还有另一个问题。

【讨论】:

  • 模式应该是pattern="^www\.(.*)",转义点。
  • @WiktorStribiżew 很好,没有额外的 \ 它匹配 www 之后的任何字符,因此如果您的域恰好是 wwwfoo.com,它会尝试重定向到 oo.com。我更正了答案
【解决方案2】:

我不会混合不同托管环境的规则; 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>

您为每个环境创建此RewriteRules.configfile 的单独版本,仅包含适当的规则并将其部署到相关的网络服务器。

这有很多好处。

  • 只评估相关环境的规则,这对性能更好。
  • 如果您有其他环境,例如 QA (http://qa. ...) 和 dev (http://dev. ...),它会更加灵活。
  • 您不必担心(和测试)一种环境的规则是否会干扰另一种环境的规则,此处:本地与实时。

RewriteRules.config 文件的部署可以包含在部署自动化中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-30
    • 2017-07-25
    • 2013-09-27
    • 1970-01-01
    • 2011-06-14
    • 2019-03-13
    • 2017-04-29
    相关资源
    最近更新 更多