Press "Enter" to skip to content

nginx image_filter 配置rewrite不生效问题

最近针对客户提供的图片大小不一,导致页面排版错乱,所以安装一个nginx的功能模块来裁剪图片,image_filter来对图片属性操作,控制图片大小,这样图片不会变形。

安装插件很快,但是配置rewrite规则同事遇到一些问题,规则不生效,一般规则xxx_100x200.jpg 或者xxx.jpg@100×200@ ,在图片后缀添加参数最好。

nginx给的默认配置都是

location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
        {
	        
            expires      30d;
        }

针对图片缓存配置,这个是通用配置,然后同事在这个规则下面 配置重新导致失败

正确的逻辑,在这个配置规则之前配置rewrite规则,最终解析需要对应到实际图片这种,逻辑顺序需要理清

location ~ (.+?)_(\d+)x(\d+)\.(gif|jpg|jpeg|png|bmp|swf)$
        {
            set $file $1_$2x$3_100.$4;
            rewrite ^.*$ $file last;
        }

        location ~ (.+?)\.(gif|jpg|jpeg|png|bmp|swf)@(\d+)x(\d+)@$
        {
            set $file $1_$3x$4_100.$2;
            rewrite ^.*$ $file last;
        }

        location ~ (.+?)_(\d+)x(\d+)_(\d+)\.(gif|jpg|jpeg|png|bmp|swf)$
        {
            
            expires 30d;
            access_log off;
            set $file $1.$5;
            set $h $2;
            set $w $3;
            set $q $4;
            

            if ($h = '0') {
                rewrite ^.*$ $file last;
            }

            if ($w = '0') {
                rewrite ^.*$ $file last;
            }

            image_filter_jpeg_quality $q;

            # 根据给定的长宽生成缩略图
            image_filter resize $h $w;
            # 根据给定的长宽剪裁图片
            image_filter crop $h $w;
            # 原图最大2M,要裁剪的图片超过2M返回415错误,需要调节参数image_filter_buffer
            image_filter_buffer 20M;

            # error_page 415 /notfound.jpg;
            try_files $file =404;
            
        }

        location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
        {
	        
            expires      30d;
        }
Leave a Reply

Your email address will not be published. Required fields are marked *

Exit mobile version