Skip to content

Instantly share code, notes, and snippets.

@gingerbeardman
Last active August 19, 2024 17:22
Show Gist options
  • Save gingerbeardman/447a20fbf15e694ee96e6f30e65cdb2a to your computer and use it in GitHub Desktop.
Save gingerbeardman/447a20fbf15e694ee96e6f30e65cdb2a to your computer and use it in GitHub Desktop.
transform local image paths to use your own CDN server
# file: _plugins/cdn_img.rb
module Jekyll
class CDNImageTransformer < Generator
def generate(site)
@site = site
@cdn_url = "https://cdn.example.com"
@site.pages.each { |page| process(page) }
@site.posts.docs.each { |post| process(post) }
end
def process(item)
item.content = item.content.gsub(/!\[(.*?)\]\((\/images\/.*?)\)/) do |match|
alt_text = $1
image_path = $2
"![#{alt_text}](#{@cdn_url}#{image_path})"
end
end
end
end
@gingerbeardman
Copy link
Author

gingerbeardman commented Aug 19, 2024

Assumptions:

  • local images folder
  • you have a single CDN domain with the same images folder structure

I use this to serve images from a domain that points to a free OCI (Oracle Cloud Infrastructure) server, whilst my HTML is served by Netlify.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment