nginx+lua 生成缩略图 核心代码
访问缩略图修改 nginx.conf 文件:
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
root /yizuotu.net/images/;
location / {
root html;
index index.html;
}
location ~* (.*\.(jpg|jpeg|gif|png))_(\d+)x(\d+)\.(jpg|jpeg|gif|png)$ {
if (!-f $request_filename) {
set $request_filepath /yizuotu.net/images/$1;
set $width $3;
set $height $4;
set $ext $5;
content_by_lua_file /usr/local/nginx/lua/yizuotu.net.lua;
}
# 注意:改配置必须放在 if 之后
root /yizuotu.net/images/images/;
}
}
在 /usr/local/nginx/lua/ 目录下创建 yizuotu.net.lua 文件,内容如下:
local command = "/usr/local/imagemagick/bin/convert -strip " .. ngx.var.request_filepath ..
" -resize " .. ngx.var.width .. "x" .. ngx.var.height .. " +profile \"*\" " .. ngx.var.request_filepath .. "_"
.. ngx.var.width .. "x" .. ngx.var.height .. "." .. ngx.var.ext;
os.execute(command);
ngx.exec(ngx.var.request_uri);
重启 Nginx 访问图片,在原图 url 后添加缩略图尺寸(_600x600.png):
访问地址:https://yizuotu.net/images/1.png_600x600.png
注意:请自行安装lua和imagemagick