通过 Nginx-Lua 自动转换图片为 WebP 格式

这几天一直在研究nginx完全自适应WebP,果然功夫不负有心人,还真成功了,思路就是:用户访问一张图片,nginx收到请求判断浏览器是否支持WebP,如果支持则返回WebP,不支持则返回原图。

先安装libwebp

wget "http://downloads.webmproject.org/releases/webp/libwebp-0.6.0-linux-x86-64.tar.gz"

tar --strip-components 1 -xzvf libwebp*.gz -C /usr/local

运行cwebp看看是否安装成功。

接下来是nginx要重新编译让他支持nginx lua模块(lnmp.org环境为例)

wget https://github.com/openresty/lua-nginx-module/archive/v0.10.11.zip

unzip v0.10.11.zip

wget https://github.com/simpl/ngx_devel_kit/archive/v0.3.0.zip

unzip v0.3.0.zip

wget http://luajit.org/download/LuaJIT-2.0.5.zip

unzip LuaJIT-2.0.5.zip

cd LuaJIT-2.0.5

make

make install PREFIX=/usr/local/luajit

cat > /etc/ld.so.conf.d/luajit.conf<<EOF
/usr/local/luajit/lib
EOF

ldconfig

export LUAJIT_LIB=/usr/local/luajit/lib

export LUAJIT_INC=/usr/local/luajit/include/luajit-2.0

然后编辑lnmp1.4/lnmp.conf文件,在Nginx_Modules_Options这一行的单引号里面添加

--with-ld-opt=-Wl,-rpath,/usr/local/luajit/lib --add-module=/root/lua-nginx-module-0.10.11 --add-module=/root/ngx_devel_kit-0.3.0

保存之后重新编译nginx,./upgrade.sh nginx,推荐1.13.6。

编译成功了之后,打开/usr/local/nginx/conf/nginx.conf文件,在http段添加

lua_package_path "/usr/local/luajit/share/luajit-2.0.5/jit/?.lua;";

然后进入/usr/local/nginx/conf文件夹,新建一个webp.lua文件,内容如下

function file_exists(name)
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); -- 去掉 .webp 的后缀

if not file_exists(originalFile) then -- 原文件不存在
ngx.exit(404);
return;
end

os.execute("cwebp -q 75 " .. originalFile .. " -o " .. newFile); -- 转换原图片到 webp 格式,这里的质量是 75 ,你也可以改成别的

if file_exists(newFile) then -- 如果新文件存在(转换成功)
ngx.exec(ngx.var.uri) -- Internal Redirect
else
ngx.exit(404)
end

之后进入/usr/local/nginx/conf/vhost,找到你要用到的网站配置文件,在server段下加入以下

location ~ {
  expires 365d;
  try_files $uri $uri/ @webp; # 如果文件不存在尝试生成 webp 图片
}

location @webp{
  if ($uri ~ "/([a-zA-Z0-9-_]+)\.(png|jpg|gif|jpeg)\.webp") { # 这里可以改成你自己的路径匹配,很重要,否则可能会导致别的文件被恶意覆盖等
    content_by_lua_file "/usr/local/nginx/conf/webp.lua";
  }
}

完成以上全部之后,重启nginx:lnmp nginx restart,或者service nginx restart

访问原图的路径,并在后面加上.webp扩展名,你会发现不会404,而是一张webp的图片被加载了。并且在目录里面也存在一个webp文件。

 

 

 

借鉴了:http://blog.eqoe.cn/posts/switch-to-webp.html

发表评论

发表评论

*

沙发空缺中,还不快抢~