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 协议》,转载必须注明作者和本文链接
本帖由系统于 5年前 自动加精
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 10

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

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

5年前 评论

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

5年前 评论

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

5年前 评论

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

5年前 评论

@Wi1dcard 对。这点忘记说了

5年前 评论

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

5年前 评论

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

5年前 评论

可以剪成圆的么

5年前 评论
wenqingzzz

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

5年前 评论

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

5年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!