banner
半米牙

半米牙的笔记

分享技术、记录生活
email

Nginx+Lua+libwebp Implement Server Image Auto Conversion to WebP

The traffic and loading speed of the server have always been the focus of optimization. The goal of an excellent webpage is to ensure clear images while saving traffic and improving loading speed.

Google has introduced a new image format: WebP (Google official website), which has a higher compression ratio than similar images. With the same image quality, the file size is 40% smaller. Moreover, the support rate of mainstream browsers has reached 80%.

Check the support rate

ng1

Screenshot of the original image loading: (12.61s)

ng2

Screenshot of WebP loading: (4.72s)

ng3

It can be seen that loading WebP greatly improves the loading speed.

Installing Lua module for Nginx#

Omitted

Installing libwebp on the server#

libwebp is a tool for converting images to WebP.

yum install libwebp-tools

Test:

cwebp -q 100 1.jpg -o 1.webp

ng4

If the above information appears, it means the installation is successful.

nginx.conf#

Configuration:

Execute the lua file that converts .png.webp, .jpg.webp, and .gif.webp requests to WebP.

location /img {
    expires               365d;
    autoindex             on;
    autoindex_exact_size  on;
    try_files             $uri $uri/ @webp;
}
    
location @webp {    
    if ($uri ~ \.(png|jpg|gif)\.webp) {
        content_by_lua_file  lua/imgProcess.lua;
    }
}

ng5

imgProcess.lua#

function file_exists(name) --Method to check if a file exists
    local f=io.open(name,"r");
    if f~=nil then io.close(f) return true else return false end
 end
 
 local newFile = ngx.var.request_filename;
 local originalFile = newFile:sub(1, #newFile - 5); --Remove the .webp suffix from the requested webp image

 if not file_exists(originalFile) then
   ngx.exit(404);
   return;
 end
 
 os.execute("cwebp -q 75 " .. originalFile  .. " -o " .. newFile);  --Convert the image using libwebp

 if file_exists(newFile) then
     ngx.exec(ngx.var.uri); --Redirect to the converted webp image
 else
     ngx.exit(404); --Conversion failed: 404
 end

ng6

Check the effect#

Access the image before, there is no WebP file on the server.

ng7

When the server receives a request for .jpg.webp, it automatically generates the WebP file:

ng8

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.