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%.
Screenshot of the original image loading: (12.61s)
Screenshot of WebP loading: (4.72s)
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
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;
}
}
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
Check the effect#
Access the image before, there is no WebP file on the server.
When the server receives a request for .jpg.webp, it automatically generates the WebP file: