LoginSignup
3
1

More than 1 year has passed since last update.

CloudFront Functionsで画像のリクエストをWebPに書き換える

Posted at

CloudFront Functions

同じS3ディレクトリに .jpg.webp.png.webpなどの拡張子のWebPがある前提で

Viewer Requestに対して以下の関数を設定

function handler(event) {
    var request = event.request;    
    var uri = request.uri;
    var ua = request.headers["user-agent"].value
    if ( ua.match(/Version\/13\./) || ua.match(/Version\/12\./) || ua.match(/Version\/11\./) || ua.match(/Version\/10\./)){
        return request
    }
    else if (uri.match(/\/images\//) && (uri.match(/\.(jpe?g|png)$/)) ) {

        request.uri += ".webp";
    }
    return request;
}

古いブラウザなのでUserAgentを使用しても良いので
ua.match(/Version\/13\./) || ...の部分でWebP未対応のSafariを分岐させる。

終わりに

ちょっとしたことはLambda@Edge使わなくても実装可能

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1