Search code examples
iisurl-rewritingoutbound

IIS Outbound Rewrite Rule for srcset with multiple URLs


I have something like this in my html response:

<img 
  src="http://www.test.com/image1.jpg"
  srcset="http://www.test.com/image1-300x200.jpg 300w, http://www.test.com/image1.jpg 600w" sizes="(max-width: 600px) 100vw, 600px" />

I'd like to use IIS outbound rewrite rule to replace all references to www.test.com with www.foo.com. How can I do this when an attribute (in this case the srcset) has multiple instances of the URL?

Here's what my rule currently looks like:

<outboundRules>
    <rule name="Blog Paths" preCondition="IsBlog">
        <match filterByTags="Img, CustomTags" customTags="BlogTags" pattern="^http://www.test.com(.*)$" />
        <action type="Rewrite" value="http://www.foo.com{R:1}" />
    </rule>
    <preConditions>
        <preCondition name="IsBlog">
            <add input="{RESPONSE_Content_Type}" pattern="^text/html" />
            <add input="{RESPONSE_X_Content_Source}" pattern="^blog" />
        </preCondition>
    </preConditions>
    <customTags>
        <tags name="BlogTags">
            <tag name="img" attribute="srcset" />
        </tags>
    </customTags>
</outboundRules>

But of course only the first URL in each attribute gets overwritten:

<img 
  src="http://www.foo.com/image1.jpg"
  srcset="http://www.foo.com/image1-300x200.jpg 300w, http://www.test.com/image1.jpg 600w" sizes="(max-width: 600px) 100vw, 600px" />

How can I rewrite all instances of www.test.com to www.foo.com?


Solution

  • Change your rule as follows:

        <match filterByTags="Img, CustomTags" customTags="BlogTags" pattern="(.*)http://www.test.com(.*)" />
        <action type="Rewrite" value="{R:1}http://www.foo.com{R:2}" />