当请求是localhost /站点根目录时,如何为IIS添加无缓存头

问题描述

我在IIS 10中托管了一个网站

.js和.css文件使用此模式?v = a.b.c(其中a.b.c每次都需要用新数字更改)来版本控制,以使缓存浏览器无效。

这是网站启动的方式:

  • 用户输入www.sitename.com(在我的情况下为“ localhost”)
  • index.html文件已加载。该文件加载main.js?v = a.b.c文件,该文件加载/配置“ require.js”。从此以后,所有其他文件都由require处理(还管理html / css / js的版本控制)

我面临的问题如下: 如何使index.html的缓存浏览器无效?

我尝试使用以下IIS中的以下web.config文件发送index.html的无缓存头,如果我在浏览器URL中写入localhost / index.html则可以使用...但是如果我不这样做,则无法使用只写本地主机(在这种情况下,将加载缓存中的旧index.html)

<configuration>
 <system.web>
   <urlMappings enabled="true">
     <add url="~/" mappedUrl="~/index.html" />
   </urlMappings>
 </system.web>
 <location path="index.html">
    <system.webServer>
        <staticContent>
            <clientCache cacheControlMode="disableCache" />
        </staticContent>
    </system.webServer>
 </location>
</configuration>

我可以得到一些帮助吗?

解决方法

您可以使用iis URL重写规则设置no-cache标头:

<system.webServer>
<rewrite>
 
<outboundRules>

  <rule name="RewriteCache-Control" preCondition="old url with 301" stopProcessing="true">
    <match serverVariable="RESPONSE_Cache-Control" pattern="(.*)" />
    <conditions>
    </conditions>
    <action type="Rewrite" value="no-cache" />
  </rule>
  <preConditions>
    <preCondition name="old url with 301">
                        <add input="{URL}" pattern="index.html|^$" />
                        <add input="{RESPONSE_CONTENT_TYPE}" pattern="^text/html" />
    </preCondition>&gt;
  </preConditions>
</outboundRules>

 </rewrite>
        <tracing>
            <traceFailedRequests>
                <add path="*">
                    <traceAreas>
                        <add provider="WWW Server" areas="Rewrite" verbosity="Verbose" />
                    </traceAreas>
                    <failureDefinitions statusCodes="100-900" />
                </add>
            </traceFailedRequests>
        </tracing>
</system.webServer>

另一种方式:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

  <location path="index.html">
    <system.webServer>
      <httpProtocol>
        <customHeaders>
          <add name="Cache-Control" value="no-cache" />
        </customHeaders>
      </httpProtocol>
    </system.webServer>
  </location>

</configuration>

enter image description here