The goal

I want a service that automatically converts images to WebP, and serves the converted image when a mobile client requests the original image.

Requirements

  1. When an image is uploaded to S3, send an event to a server to convert the image to WebP
  2. After converting it into WebP, save it into the bucket
    (The WebP Server is good, but I want to serve the WebP content statically)
  3. For each mobile image request, redirect the request to the WebP image

So I tried the redirect logic first

For a reverse proxy, rewriting URLs is a basic requirement.
So this should be easy enough: just handle image extension checks and mobile User-Agent checks.

I’ll use Ferron as the example.

snippet "mobile_condition" {
    condition "is_mobile" {
        is_regex "{header:User-Agent}" "(Mobile|Android|iPhone|iPad)" case_insensitive=#true
    }
    condition "is_image" {
        is_regex "{path}" "\\.(png|jpg|jpeg)(?:$|[?#])" case_insensitive=#true
    }
}

rn.lab.s3.087870.xyz {
    proxy "http://garage:3902"

    use "mobile_condition"
    if "is_mobile" and "is_image" {
        rewrite "^/(.*).(png|jpg|jpeg)$" "/$1.webp"
    }
    proxy_request_header_replace "Host" "rn.lab.s3.087870.xyz"
}