wp-rocket icon indicating copy to clipboard operation
wp-rocket copied to clipboard

Template variables are not ignored when the srcset attribute is rewritten by the CDN add-on

Open johan-las opened this issue 7 months ago • 1 comments

Describe the bug When the CDN Add-on is activated, if inside a <script> tag we use a template variable like {{data.srcset}} within a srcset attribute, the URL in srcset is rewritten from {{data.srcset}} to http://cdn-url.com/{{data.srcset}}, which result in an error 404, as the CDN URL will be added again when using the template.

I added an error_log before the foreach, and I got:

WP Rocket CDN: Found srcset attributes to rewrite: Array
(
...
    [1] => Array
        (
            [0] =>  srcset="{{data.srcset}}"
            [sources] => {{data.srcset}}
            [1] => {{data.srcset}}
        )
   ....
)

I added an error_log after the $cdn_source, and I got:

WP Rocket CDN: Rewriting URL in srcset from {{data.srcset}} to http://cdn-url.com/{{data.srcset}}

To Reproduce Steps to reproduce the behavior:

  1. Add the following test code into a page:
<script type="text/html" id="tmpl-woo-variation-gallery-slider-template">
				<# if( !data.video_link &#038;&#038; data.srcset ){ #>
		<div  class="wvg-single-gallery-image-container">
			<img decoding="async" loading="lazy" width="{{data.src_w}}" height="{{data.src_h}}" src="{{data.src}}" alt="{{data.alt}}" title="{{data.title}}" data-caption="{{data.caption}}" data-src="{{data.full_src}}" data-large_image="{{data.full_src}}" data-large_image_width="{{data.full_src_w}}" data-large_image_height="{{data.full_src_h}}" srcset="{{data.srcset}}" sizes="{{data.sizes}}" {{data.extra_params}} />
		</div>
		<# } #>
	</script>
  1. Activate the CDN Ad-on, add a CDN URL.
  2. Go to the page, search for the

Expected behavior This kind of variable {{data.srcset}} should be ignored.

Screenshots

Image

Desktop (please complete the following information):

  • OS: MacOs
  • Browser Chrome
  • Version [e.g. 22]

Additional context

Ticket: https://secure.helpscout.net/conversation/2939585079/560806?viewId=4075513 Slack: https://group-onecom.slack.com/archives/C08F4M3BBJL/p1747733663156009

johan-las avatar May 20 '25 14:05 johan-las

Additional information:

Lucy mentioned in the Slack discussion that this case was handled in this PR.

However, Ahmed investigated further and found that the PR addressed the replacement of any URL in the page, while our current issue is different.

In our case, the problem lies in the rewrite_srcset method, it searches for any srcset attribute in the page and replaces the URLs.

To properly handle this, we also need to remove all inline scripts during the processing of srcset, specifically at this point in the code:

https://github.com/wp-media/wp-rocket/blob/a1bdab03c889b965cc55e7f8eb4d1cbaff5e83ff/inc/Engine/CDN/CDN.php#L97

johan-las avatar May 21 '25 09:05 johan-las