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

如何将Nginx图片格式适配配置转换为IIS的web.config配置?

将Nginx图片格式优先级配置转换为IIS web.config实现相同功能

需求回顾

原Nginx配置实现的逻辑:

  • 匹配请求路径为 .jpg/.jpeg/.jpe/.png/.webp 的图片资源
  • 响应头添加 Vary: Accept,告知缓存服务根据请求的Accept头区分缓存
  • 优先返回对应文件名的.avif格式文件;若不存在则返回.webp格式;若两者都不存在则返回原请求的格式文件;所有文件都不存在时返回404

对应的IIS web.config配置

以下是实现完全相同逻辑的web.config配置:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <!-- 添加Vary: Accept响应头 -->
    <httpProtocol>
      <customHeaders>
        <add name="Vary" value="Accept" />
      </customHeaders>
    </httpProtocol>

    <!-- URL重写规则,实现文件优先级匹配 -->
    <rewrite>
      <rules>
        <!-- 规则1:优先匹配对应的AVIF文件 -->
        <rule name="Serve AVIF if exists" stopProcessing="true">
          <match url="^(.+)\.(jpg|jpeg|jpe|png|webp)$" ignoreCase="true" />
          <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{DOCUMENT_ROOT}/{R:1}.avif" matchType="IsFile" />
          </conditions>
          <action type="Rewrite" url="{R:1}.avif" />
        </rule>

        <!-- 规则2:AVIF不存在时,匹配对应的WebP文件 -->
        <rule name="Serve WebP if exists" stopProcessing="true">
          <match url="^(.+)\.(jpg|jpeg|jpe|png|webp)$" ignoreCase="true" />
          <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{DOCUMENT_ROOT}/{R:1}.webp" matchType="IsFile" />
          </conditions>
          <action type="Rewrite" url="{R:1}.webp" />
        </rule>

        <!-- 规则3:若以上都不存在,保留原请求,IIS会自动返回原文件或404 -->
        <rule name="Serve original file or 404" stopProcessing="true">
          <match url="^(.+)\.(jpg|jpeg|jpe|png|webp)$" ignoreCase="true" />
          <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsFile" />
          </conditions>
          <action type="None" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

配置说明

  1. 响应头设置:通过<customHeaders>添加Vary: Accept,和原Nginx的add_header Vary Accept作用完全一致。
  2. 规则1(AVIF优先):匹配目标图片后缀的请求,先检查原请求文件是否不存在(避免原文件存在时仍重写),再检查对应.avif文件是否存在,存在则重写路径返回AVIF文件。
  3. 规则2(WebP次之):若AVIF文件不存在,检查对应.webp文件是否存在,存在则重写路径返回WebP文件。
  4. 规则3(原文件兜底):如果原请求的文件存在,直接返回原文件;若原文件也不存在,IIS会自动返回404状态码,符合需求逻辑。

注意事项

  • 确保你的IIS服务器已安装URL Rewrite模块,否则重写规则无法生效。
  • ignoreCase="true"确保匹配不区分大小写,适配Windows文件系统的特性。
  • 规则的顺序不可调整,必须按照AVIF→WebP→原文件的优先级排列。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 05:18:09