IIS重写规则 - 忽略localhost
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了IIS重写规则 - 忽略localhost相关的知识,希望对你有一定的参考价值。
我有以下规则,它可以很好地将我的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>
你能帮忙吗?正则表达是我的弱点唉
答案
如果使用条件仅匹配以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
而无需重定向。也许这里还有另一个问题。
另一答案
我不会混合不同托管环境的规则; 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文件的部署可以包含在部署自动化中。
以上是关于IIS重写规则 - 忽略localhost的主要内容,如果未能解决你的问题,请参考以下文章
使用反向代理的 IIS URL 重写规则 - HTTP 错误 500.52