You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Web.config中HSTS重写规则配置后响应头缺失问题排查

解决HSTS响应头未出现的配置问题

我帮你排查出两处关键配置错误,咱们一步步修正:

1. HTTP转HTTPS规则的条件完全写错了

你当前的HTTP重定向规则里,条件部分写的是:

<add input="{HTTPS}" pattern="^test\.test\.test$" ignoreCase="true" />

{HTTPS}这个服务器变量的取值只有on(HTTPS请求)或者off(HTTP请求),根本不会是你的域名!这个条件永远不会触发,导致HTTP请求压根不会被重定向到HTTPS。

正确的条件应该是检查{HTTPS}是否为off,这样所有HTTP请求才会被强制转到HTTPS:

<conditions>
  <add input="{HTTPS}" pattern="off" ignoreCase="true" />
</conditions>

2. 出站规则的匹配逻辑不生效

你的出站规则里,match节点的pattern=".*"意味着:只有当RESPONSE_Strict_Transport_Security这个响应头已经存在(有任意内容)时,才会执行重写操作。但默认情况下这个头是不存在的,所以规则根本不会触发。

你需要修改match节点,添加negate="true",表示当响应头不存在时才执行规则:

<match serverVariable="RESPONSE_Strict_Transport_Security" pattern=".*" negate="true" />

修正后的完整配置

把两处错误修正后,你的rewrite节点应该是这样的:

<rewrite>
  <rules>
    <rule name="HTTP to HTTPS redirect" enabled="true" stopProcessing="true">
      <match url="(.*)" />
      <conditions>
        <add input="{HTTPS}" pattern="off" ignoreCase="true" />
      </conditions>
      <action type="Redirect" url="https://test.test.test/{R:1}" redirectType="Permanent" />
    </rule>
  </rules>
  <outboundRules>
    <rule name="Add Strict-Transport-Security when HTTPS" enabled="true">
      <match serverVariable="RESPONSE_Strict_Transport_Security" pattern=".*" negate="true" />
      <conditions>
        <add input="{HTTPS}" pattern="on" ignoreCase="true" />
      </conditions>
      <action type="Rewrite" value="max-age=31536000; includeSubDomains; preload" />
    </rule>
  </outboundRules>
</rewrite>

额外注意事项

  • 确认你的IIS安装了URL Rewrite 2.0及以上版本,旧版本不支持出站规则。
  • 测试时可以直接访问HTTPS地址,或者先访问HTTP触发重定向后,再用F12检查响应头(HSTS头只会在HTTPS请求中返回)。
  • 如果用了CDN或反向代理,要确保它们没有移除这个响应头,并且正确传递了{HTTPS}变量。

内容的提问来源于stack exchange,提问作者Prany

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 06:28:10