在IIS上仅为Font文件启用CORS

问题描述 投票:7回答:3

有没有办法在IIS7上只为特定类型的文件启用CORS?我将离开这篇文章(https://www.maxcdn.com/one/tutorial/how-to-use-cdn-with-webfonts/)并注意到Apache和nginx示例显示只有在请求查找某个Content-Type时才启用CORS,而IIS示例显示为所有内容启用了CORS。

我有一个外部网站上引用的CSS,但浏览器阻止了字体文件,并希望在IIS7上启用CORS,但仅限于.woff,.woff2,.tff,.eot和.svg文件。如果可能的话,我不希望为所有内容启用CORS。

fonts iis-7 web-config cors
3个回答
-1
投票

您可以安装IIS重写模块https://www.microsoft.com/en-us/download/details.aspx?id=7435。安装模块后,重新启动IIS管理器,然后单击“站点”节点下的网站。如果您在IIS部分右侧的窗口中看到URL重写模块符号(如下所示),那么您就可以开始:

enter image description here

然后在Web.config上,您需要添加以下规则:

<rewrite>
 <rules>
  <rule name="Add Cross Origin Access">
    <match serverVariable="RESPONSE_Access_Control_Allow_Origin" pattern=".*" />
    <conditions>
      <add input="{REQUEST_URI}" pattern="^[^\?]+\.(ttf|otf|eot|woff|woff2|svg)(\?.*)?$" />
    </conditions>
    <action type="Rewrite" value="*"/>
  </rule>
 </rules>
</rewrite>

23
投票

Hackerman的答案很棒,它让我找到了解决方案,然而,我必须做出一些调整。第一个是将规则放在outboundRules节点下的rewrite部分。

<outboundRules>
    <rule name="Enable CORS for Fonts">
        <match serverVariable="RESPONSE_Access_Control_Allow_Origin" pattern=".*" />
        <conditions>
          <add input="{REQUEST_URI}" pattern="^[^\?]+\.(ttf|otf|eot|woff|woff2|svg)(\?.*)?$" />
        </conditions>
        <action type="Rewrite" value="*" />
    </rule>
</outboundRules>

最后,正则表达式已更新,以防止下面的请求,这将允许有人请求跨源的任何URL:

/some/critical/javascript/file.js?v=.woff
/api/secure/users?v=.woff

......但它仍然允许以下内容

/some/font.woff
/some/font.woff?etag
/some/font.woff?v=123

12
投票

您应该将此代码添加到Web.config:

  <location path="fonts/FontName.ttf">
    <system.webServer>
       <httpProtocol>
          <customHeaders>
             <add name="Access-Control-Allow-Origin" value="*" />
          </customHeaders>
       </httpProtocol>
    </system.webServer>
  </location>
© www.soinside.com 2019 - 2024. All rights reserved.