在做web开发时,图片属于静态资源,可使用Nginx的静态目录输出图片,以节省后端服务珍贵的请求
同时,图片输出地址还需要支持参数化的缩略图请求,以减少宝贵的带宽资源
使用Nginx的image-filter 模块可以非常优雅地完成需求
1. 安装Nginx,默认会把image-filter模块也安装了
apt-get install nginx
2. 配置location
location ~* .(jpg|gif|png)$ {
image_filter demo;
root /var/www/html/images;
set $width -; # xxx.jpg?width=100
set $height -; # xxx.jpg?height=100
if ($arg_width != "") {
set $width $arg_width;
}
if ($arg_height != "") {
set $height $arg_height;
}
image_filter resize $width $height; # 缩放图片
image_filter_buffer 10M; # 设置nginx读取图片最大buffer
image_filter_interlace on; # 是否开启图片隔行扫描
error_page 404 = 400.html;
}
3. 测试
xxx.jpg?width=100&height=200
xxx.jpg 图片会按长宽缩放