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 协议》,转载必须注明作者和本文链接
提示:默认 Nginx 是没有编译此模块的。需要使用
--with-http_image_filter_module
参数编译。参考:http://nginx.org/en/docs/http/ngx_http_ima...
另外有个问题,
location /image_resize
没有deny
,所以任意人可以通过访问此 URL 压缩图片。这活交给php干不更灵活吗?
@CorePlusPlus 这个是根据请求参数动态裁剪的
@Wi1dcard 对。这点忘记说了
@woann yum install nginx 安装的,怎么加上
--with-http_image_filter_module
@lovecn 你这个只能重新源码编译,编译很简单啊
可以剪成圆的么
@CorePlusPlus php挂了怎么办,直接返回更好
@wenqingzzz 这话说的 那服务器宕机了怎么办?PHP生成图片文件 交给nginx不就完了
@woann 后期要实现加水印 加特效这些呢?所以说PHP更灵活 nginx还是干本职工作就行了