banner
半米牙

半米牙的笔记

分享技术、记录生活
email

Nginx+Lua+libwebp implementation for server-side automatic image 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 launched a new image format: WebP (Google official website), which has a higher compression ratio compared to similar image formats. With the same image quality, the file size is 40% smaller. Moreover, the support rate of mainstream browsers has reached 80%.

Check support rate

ng1

Screenshot of original image loading: (12.61s)

ng2

Screenshot of WebP image 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

Testing:

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

ng4

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

nginx.conf#

Configuration:

Let requests for .png.webp, .jpg.webp, and .gif.webp execute the lua file for converting 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

Checking the effect#

Accessing the image before, there are no WebP files 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.