IIS重写规则在生产环境中不起作用

8
我在Azure中有4个服务器,其中3个是负载均衡的,第4个仅用于CMS目的。
主网站已添加SSL证书,但是CMS所在的子域没有添加证书。
我编写了一个规则,应该可以找到任何不包含“backoffice”的URL,并匹配任何其他页面来将其更改为https。
在regexr.com上这个规则可行,但由于某种原因,在实际环境中却无法正常工作。
<rewrite>
        <rules>
            <rule name="http to https" stopProcessing="true">
                <match url="(https?:\/\/(?!backoffice).*)" />
                <conditions>
                    <add input="{HTTPS}" pattern="^OFF$" />
                </conditions>
                <action type="Redirect" url="https://www.WEBSITENAME.com{R:1}" />
            </rule>
        </rules>
    </rewrite>

所有4台服务器都已安装Url Rewriting 2.1,并且我在Azure中创建了一个负载均衡集合以用于https。手动访问https(连同负载平衡)可以正常工作。
其他信息:我尝试了很多规则,包括现有的答案。我可以看到发生的事情,比如资产被作为https引入,但页面本身没有重定向。有2个负载平衡集合,一个用于80端口,另一个用于443端口。我不知道这是否正确,或者可能是重定向未发生的潜在原因。

如果您将正则表达式替换为<match url="(.*)" />,会发生什么?这样行得通吗? - evilSnobu
重定向仍未发生。此外,CSS/JS/图像未加载,表明混合HTTP/HTTPS。 - Hazonko
2个回答

5

您的规则应该是这样的:

<rule name="http to https" stopProcessing="true">
    <match url=".*" />
    <conditions>
        <add input="{HTTPS}" pattern="^OFF$" />
        <add input="{REQUEST_URI}" pattern="/backoffice" negate="true" />
    </conditions>
    <action type="Redirect" url="https://www.WEBSITENAME.com{R:0}" />
</rule>

这个规则将会排除路径为/backoffice的请求。

另外,为了解决混合内容的问题,您需要将css/js/images的路径更改为相对路径。例如:

<img src="/path/to/your/image.jpg"/>

另一种解决混合内容的方法是创建出站规则,这将更改您的输出HTML(将http:替换为https:):
<rewrite>

  ...

  <outboundRules>
    <rule name="Rewrite external references to use HTTPS" preCondition="IsHTML">
      <match filterByTags="Script, Link, Img, CustomTags" customTags="HTML5Tags" pattern="^http://(.*)$" />
      <action type="Rewrite" value="https://{R:1}" />
    </rule>
    <preConditions>
      <preCondition name="IsHTML">
        <add input="{RESPONSE_CONTENT_TYPE}" pattern="^text/html" />
      </preCondition>
    </preConditions>
    <customTags>
      <tags name="HTML5Tags">
        <tag name="Video" attribute="src" />
      </tags>
    </customTags>
  </outboundRules>
</rewrite>

后台管理是一个子域名而不是一个文件夹,但我会尝试一下。 - Hazonko
否定在后台运行。但是我在客户端得到了奇怪的结果。所有的图像都无法加载,返回 301 错误。这是因为页面本身实际上没有重定向到 HTTPS。 - Hazonko
离开一周后回到办公室...我在想,否定可能根本没有起作用。因为它根本没有重定向页面。我可以看到所有的图像都有301的标记,说明它们已经移动到https,但它们并没有重定向,页面也没有重定向。 - Hazonko

5

以之前的答案为出发点,我做了一些小改动,使用HTTP_HOST而不是REQUEST_URI进行模式否定,这样就可以正常工作。

<system.webServer>
    <rewrite xdt:Transform="InsertIfMissing">
        <rules>
            <rule name="http to https" stopProcessing="true">
                <match url=".*" />
                <conditions>
                    <add input="{HTTPS}" pattern="^OFF$" />
                    <add input="{HTTP_HOST}" pattern="^backoffice\.WEBSITENAME\.com$" negate="true" />
                </conditions>
                <action type="Redirect" url="https://www.WEBSITENAME.com/{R:0}" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

我认为维克多应该得到奖励,因为他不可能知道这个细节 :) - Christian Müller
当然是真的,而且他也帮助我得出了结论。 - Hazonko

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接