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

如何调整URL Rewrite规则仅改写指定文件夹的相对URL

修改URL Rewrite规则以限制特定文件夹的资源改写

没问题,我来帮你调整这个正则表达式,精准把改写范围限制到/media或/css开头的相对资源链接上~

修改后的完整规则配置

<outboundRules>
  <clear />       
  <rule name="CDN" preCondition="CheckHTML" enabled="true" stopProcessing="true">
    <match filterByTags="Img, Link, Script, CustomTags" customTags="Video" pattern="(^(?!www\.|(?:http|ftp)s?:\/\/|[A-Za-z]:\\|\/\/)\/(media|css)\/.*\.(jpg|jpeg|png|js|css|mp4).*)" />
    <action type="Rewrite" value="http://cdn.example.com{R:1}" />
    <conditions logicalGrouping="MatchAll">
    </conditions>
  </rule>   
  <preConditions>
    <preCondition name="CheckHTML">
      <add input="{RESPONSE_CONTENT_TYPE}" pattern="^text/html" />
   </preCondition>
  </preConditions>
  <customTags>
    <tags name="Video">
      <tag name="source" attribute="src" />
    </tags>
  </customTags>           
</outboundRules>

核心正则修改说明

原来的正则是匹配所有非绝对路径的指定后缀资源,我重点修改了匹配模式的中间部分:

  • 保留了开头的否定前瞻 ^(?!www\.|(?:http|ftp)s?:\/\/|[A-Za-z]:\\|\/\/):确保只处理相对路径(排除绝对URL、本地磁盘路径、跨域相对路径等)
  • 新增了\/(media|css)\/:强制要求路径必须以/media/或/css/开头(这里的\/是正则里对斜杠的转义写法)
  • 后面的.*用来匹配文件夹下的任意子路径和文件名,最后保留原来的后缀匹配规则

可选调整:支持不带开头斜杠的相对路径

如果你的代码里存在类似media/file.jpg(而非/media/file.jpg)的相对链接,你可以把正则改成下面这样,同时兼容两种写法:

(^(?!www\.|(?:http|ftp)s?:\/\/|[A-Za-z]:\\|\/\/)(?:\/media\/|\/css\/|media\/|css\/).*\.(jpg|jpeg|png|js|css|mp4).*)

这样配置后,规则就只会改写/media/xxx、/css/xxx(或不带开头斜杠的对应路径)下的指定后缀资源,其他路径的相对链接会被忽略啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:14:23