nginx 实现动态生成缩略图 已在线上实际应用
场景#
假设现在有一个项目,目录为 /home/wwwroot/test,项目保存原图的路径是 /home/wwwroot/test/public/uploads,现在创建缩略图的缓存目录 /home/wwwroot/test/public/cache, 假设你的 nginx 配置文件分为 nginx.conf,并且针对单个项目有子配置文件(如 www.test.com.conf),nginx.conf 中引入了 www.test.com.conf
前提:nginx 要在编译时加
--with-http_image_filter_module
参数,也就是添加图片裁剪的功能模块
1. 配置文件 nginx.conf, 在原有配置的基础上添加 8080 端口监听:
2. 配置文件 nginx.conf, 在原有配置的基础上添加压缩处理图片的功能 (image_resize):
3. 配置文件 www.test.com.conf, 在原有配置的基础上添加接收压缩图片的请求处理:
处理流程#
-
假设有一张原图,在 /home/wwwroot/test/public/uploads/1.jpg 下,原图 url:http://www.test.com/uploads/1.jpg
-
当请求 url:http://www.test.com/resize_100x100/uploads/1.jpg 时,这个请求进入了 location ~* ^/resize, 接着判断 image_path 这个目录下是否存在这张图片,如果存在直接返回给用户
-
如果不存在,则转发到 http://127.0.0.1:8080/image_resize/uploads/1.jpg?width=100&height=100;
-
image_resize 将图片裁剪压缩并缓存到服务器本地 /home/wwwroot/test/public/cache/resize_100x100/uploads/1.jpg, 并返
配置代码(nginx.conf):#
listen 8080;
location /image_resize {
alias /home/wwwroot/yamecent/admin/public;#源文件路径
image_filter crop $arg_width $arg_height;
image_filter_jpeg_quality 75;
access_log off;
}
配置代码(www.test.com.conf):#
location ~* ^/resize {
root /home/wwwroot/test/public/cache;#初始加载路径
set $width 150;
set $height 100;
set $dimens "";
if ($uri ~* "^/resize_(\d+)x(\d+)/(.*)" ) {
set $width $1;
set $height $2;
set $image_path $3;
set $demins "_$1x$2";
}
if ($uri ~* "^/resize/(.*)" ) {
set $image_path $1;
}
set $image_uri image_resize/$image_path?width=$width&height=$height;
if (!-f $request_filename) {
proxy_pass http://127.0.0.1:8080/$image_uri;
break;
}
proxy_store on;
proxy_temp_path /home/wwwroot/test/public/cache;#缓存路径
proxy_store_access user:rw group:rw all:r;
proxy_set_header Host $host;
access_log on;
}
效果#
如有疑问请评论或者联系 qq304550409
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: