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, 在原有配置的基础上添加接收压缩图片的请求处理:

处理流程#

配置代码(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 协议》,转载必须注明作者和本文链接
本帖由系统于 6年前 自动加精
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 10

提示:默认 Nginx 是没有编译此模块的。需要使用 --with-http_image_filter_module 参数编译。

参考:http://nginx.org/en/docs/http/ngx_http_ima...

6年前 评论

另外有个问题,location /image_resize 没有 deny,所以任意人可以通过访问此 URL 压缩图片。

6年前 评论

这活交给 php 干不更灵活吗?

6年前 评论

@CorePlusPlus 这个是根据请求参数动态裁剪的

6年前 评论

@Wi1dcard 对。这点忘记说了

6年前 评论

@woann yum install nginx 安装的,怎么加上 --with-http_image_filter_module

6年前 评论

@lovecn 你这个只能重新源码编译,编译很简单啊

6年前 评论

可以剪成圆的么

6年前 评论
wenqingzzz

@CorePlusPlus php 挂了怎么办,直接返回更好

6年前 评论

@wenqingzzz 这话说的 那服务器宕机了怎么办?PHP 生成图片文件 交给 nginx 不就完了
@woann 后期要实现加水印 加特效这些呢?所以说 PHP 更灵活 nginx 还是干本职工作就行了

6年前 评论