Rewrite file urls to get thumbs from CDN

Hi, I wanted to use KeyCDN for image thumbs but can’t manage to rewrite the urls.
I created a little plugin, (inspired by several other suggestions in the forum and recipies):

Kirby::plugin('my/urls', [
  'components' => [
    'file::url' => function ($kirby, $file): string {
      if (option('cdn', false) !== false) {
        return 'https://' . option('cdn.host') . '/' . 'media/pages/' . $file->parent()->id() .'/'. $file->mediaHash() .'/'. $file->filename();
      }
      return $file->url();
    }
  ]
]);

In my templates, when I call $image->url() the url is properly rewritten and points to the cdn. But for $image->resize(600)->url() or $image->srcset() it is not and the old url from my own host appears.

How can I also rewrite image urls for resized thumbs and srcset?

I also tried the more generic url component, but that doesn’t help either.
Thanks for any help!

1 Like

There’s also file versions that need to be adapted: https://getkirby.com/docs/reference/plugins/components/file-version

You can find an example in the getkirby.com repo

I see, thank you! It now works.
I took the component from your cloudinary plugin and just replaced the url:

'file::version' => function (App $kirby, File $file, array $options = []) {
    static $originalComponent;

    if (option('cdn', false) !== false) {
        // replacing the url
        $url = 'https://' . option('cdn.host') . '/' . 'media/pages/' . $file->parent()->id() .'/'. $file->mediaHash() .'/'. $file->filename();
        return new FileVersion([
            'modifications' => $options,
            'original'      => $file,
            'root'          => $file->root(),
            'url'           => $url,
        ]);
    }

    if ($originalComponent === null) {
        $originalComponent = (require $kirby->root('kirby') . '/config/components.php')['file::version'];
    }
    return $originalComponent($kirby, $file, $options);
}

I don’t know if there is a smarter or simpler way to do it or if this whole $originalComponent stuff is necessary, but it works for now. Thank you!