Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If Chrome, use WebP

Because currently only Chrome and Opera supports WebP, I was wondering if I could target those two particular browsers and redirect them to fetch another version of my website so I can help optimize my site downloading speed more faster?

Thanks.

like image 1000
level3 Avatar asked Sep 05 '25 17:09

level3


2 Answers

I solved this problem like this:

  • Check if the client advertises "image/webp" in Accept header
  • If WebP is supported, check if the local WebP file is on disk, and serve it
  • If server is configured as proxy, append a "WebP: true" header and forward to backend
  • Append "Vary: Accept" if a WebP asset is served

in Nginx:

location / {
    if ($http_accept ~* "webp") { set $webp "true"; }
    # Use $webp variable to add correct image. 
}

In my case, I use thumbor software to convert images. https://github.com/globocom/thumbor

pip install thumbor

My conf:

upstream thumbor  {
    server 127.0.0.1:9990;
    server 127.0.0.1:9991;
    server 127.0.0.1:9992;
    server 127.0.0.1:9993;
    server 127.0.0.1:9994;
}
location / {
    if ($http_accept ~* "webp") {
        set $webp "T";
    }
    if ($uri ~* "(jpg|jpeg)$") {
         set $webp "${webp}T";
    }
    proxy_cache_key $host$request_uri$webp;

    if ($webp = "TT") {
        rewrite ^(.*)$ "/unsafe/smart/filters:format(webp)/exemple.com$uri" break;
        proxy_pass http://thumbor;
        add_header Content-Disposition "inline; filename=image.webp";
    }
    if ($webp != "TT") {
        proxy_pass http://exemple.com;
    }
}
like image 104
Cícero Verneck Corrêa Avatar answered Sep 07 '25 18:09

Cícero Verneck Corrêa


For a while now, thumbor supports automatic webp conversion:

https://github.com/thumbor/thumbor/wiki/Configuration#auto_webp

You'll still have to configure the load balancer to pass the webp accepts header, but other than that, thumbor will take care of everything for you.

Hope that helps!

like image 34
user2429739 Avatar answered Sep 07 '25 18:09

user2429739