Nginx的ngx_http_image_filter_module模块(适用于0.7.54及以上版本)能够动态调整JPEG、GIF、PNG及WebP格式图片的尺寸。
该功能模块在默认安装状态下并未包含,必须通过添加--with-http_image_filter_module配置选项才能激活。
当网站图片流量负载较低时,采用此模块进行动态处理是可行的方案。
模块底层依赖于libgd图形库,建议升级至该库的最新稳定版本以确保兼容性。
以下流程介绍如何在已部署的Nginx环境中追加该模块。
第一步:安装依赖包
yum -y install gd-devel
yum -y install libxslt-devel
yum -y install perl-devel perl-ExtUtils-Embed
第二步:检查现有Nginx编译参数
nginx -V
执行命令后输出结果如下所示:
nginx version: nginx/1.12.2 configure arguments:
检查输出中是否包含--with-http_image_filter_module字样;若存在则表明模块已就绪,否则需继续后续安装步骤。
第三步:重新编译源码
编译前需下载与原Nginx相同版本的源代码包并进行解压。
在configure命令中加入--with-http_image_filter_module=dynamic选项,同时保留原有的所有配置参数(注意:无需执行make install进行覆盖安装)。
./configure --with-http_image_filter_module=dynamic
make
第四步:备份原有Nginx目录
cp -r /usr/local/nginx /usr/local/nginxbak
第五步:替换二进制文件
cp objs/nginx /usr/local/nginx/sbin/
mkdir /usr/local/nginx/module
cp objs/ngx_http_image_filter_module.so /usr/local/nginx/module/ngx_http_image_filter_module.so
第六步:编辑Nginx配置文件
使用vim编辑器打开/usr/local/nginx/conf/nginx.conf文件。
load_module /usr/local/nginx/module/ngx_http_image_filter_module.so;
location ~* /images/(.+)_(\d+)x(\d+)\.(jpg|jpeg|gif|png)$ {
set $w $2;
set $h $3;
image_filter resize $w $h;
image_filter_buffer 30M; #设置图片缓冲区的最大大小,大小超过设定值,服务器将返回错误415
image_filter_interlace on;
image_filter_jpeg_quality 80;
try_files /$1.$4 /notfound.jpg;
expires 1d;
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
alias /home/publisherupload/ ; #root 能够让访问 /images/ 路径时,访问到 /User/XX/Desktop/images,如果将 root 替换为 alias,则访问的是 /User/XX/Desktop/;其中 /User/XX/Desktop/ 是本机中的绝对路径。
}
location /images {
alias /home/publisherupload/ ; #root 能够让访问 /images/ 路径时,访问到 /User/XX/Desktop/images,如果将 root 替换为 alias,则访问的是 /User/XX/Desktop/;其中 /User/XX/Desktop/ 是本机中的绝对路径。
autoindex on; #打开目录浏览功能
}
第七步:重载Nginx服务配置
/usr/local/nginx/sbin/nginx -s
第八步:功能测试验证
最终访问地址需在原图片URL后附加_宽度X高度的参数后缀。
http://110.87.103.58:12345/images/2026-01/202601250944272_500x400.png
参考资料
https://cloud.tencent.com/developer/article/1644466
至此,关于利用Nginx动态转换图片尺寸以生成缩略图的教程已结束,如需了解更多相关技术细节,请查阅本站历史文章或继续关注后续更新,感谢支持。