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

IIS Rewrite规则异常:外部图片URL仍被强制转为WebP

解决IIS Rewrite转换外部图片为WebP的问题

你当前的规则中,入站(inbound)规则的{HTTP_HOST}条件是有效的——它处理的是用户直接请求到你服务器的图片资源,此时HTTP_HOST确实是你的域名。但出站(outbound)规则是用来修改HTML响应中的图片链接,这里的{HTTP_HOST}条件完全无效:它始终是当前网站的域名,不管HTML里的图片是来自你自己的服务器还是外部站点,这个条件都会匹配成功,导致所有图片链接都被追加.webp,外部图片自然返回404。

解决方案:针对出站规则的图片链接做来源校验

要解决这个问题,你需要在出站规则中直接判断HTML里的图片URL是否属于本站,只处理站内图片,排除外部链接。以下是两种可行的实现方式:

方式1:仅匹配本站域名或相对路径的图片

修改出站规则的匹配模式,只捕获包含你域名的绝对路径图片,或者本站的相对路径图片:

<outboundRules rewriteBeforeCache="true">
    <rule name="jpg to webp" preCondition="ResponseIsHtml" enabled="true">
        <!-- 只匹配本站域名或相对路径的jpg/png图片 -->
        <match filterByTags="Img" pattern="^(https?://mydomain.com/|/)(.+\.(jpe?g|png))$" ignoreCase="true" />
        <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
            <add input="{HTTP_ACCEPT}" pattern="image/webp" ignoreCase="false" />
            <add input="{URL}" pattern="typo3/" negate="true" />
            <add input="{URL}" pattern="fileadmin/" negate="true" />
            <add input="{URL}" pattern="uploads/" negate="true" />
        </conditions>
        <action type="Rewrite" value="{R:1}{R:2}.webp" />
    </rule>
    <preConditions>
        <preCondition name="ResponseIsHtml">
            <add input="{RESPONSE_CONTENT_TYPE}" pattern="^text/html" />
        </preCondition>
    </preConditions>
</outboundRules>

方式2:直接排除外部绝对路径的图片

在出站规则的条件中添加判断,排除所有以http://或https://开头的外部链接:

<outboundRules rewriteBeforeCache="true">
    <rule name="jpg to webp" preCondition="ResponseIsHtml" enabled="true">
        <match filterByTags="Img" pattern="(.+\.(jpe?g|png))$" ignoreCase="true" />
        <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
            <!-- 排除外部绝对路径图片 -->
            <add input="{URL}" pattern="^https?://" negate="true" />
            <add input="{HTTP_ACCEPT}" pattern="image/webp" ignoreCase="false" />
            <add input="{URL}" pattern="typo3/" negate="true" />
            <add input="{URL}" pattern="fileadmin/" negate="true" />
            <add input="{URL}" pattern="uploads/" negate="true" />
        </conditions>
        <action type="Rewrite" value="{R:0}.webp" />
    </rule>
    <preConditions>
        <preCondition name="ResponseIsHtml">
            <add input="{RESPONSE_CONTENT_TYPE}" pattern="^text/html" />
        </preCondition>
    </preConditions>
</outboundRules>

关键说明

  • 出站规则的核心是要针对图片链接本身做来源判断,{HTTP_HOST}在这个场景下无法识别图片的实际域名,必须直接校验URL格式。
  • 建议在出站规则中同步添加{HTTP_ACCEPT}条件,确保只有支持WebP的浏览器才会被替换链接,和入站规则逻辑保持一致。

内容的提问来源于stack exchange,提问作者SECØND BANANA

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 06:01:05