nginx图片缩放的默认参数
需求:picxxx.jpg图片显示原图,原图大小不固定,由于其他缩放的规则所限,必须放在location中强匹配。另外在jpg后面加上?后,传入参数,按照参数缩放。
原url:http://xxx.com/lpic/1cd/ee5/3c4/bcb5b0167f15adda2d51e795606daa33.jpg
缩放url:http://xxx.com/lpic/1cd/ee5/3c4/bcb5b0167f15adda2d51e795606daa33.jpg?size=cp120x60
做法:
location ~* ^/(.+)/(.+)/(.+)/(.+)/(.*\.(jpg|png|gif)) { set $width "-"; set $height "-"; root /xxxx/storage; if ( $request_uri ~* ^/(.+)/(.+)/(.+)/(.+)/(.*\.(jpg|png|gif))\?size=cp([0-9]+)x([0-9]+) ) { set $width $7; set $height $8; } image_filter crop $width $height ; image_filter_jpeg_quality 70; }
注意到两个set部分,因为原图大小并不知道,而因为在location中还需要crop,所以需要赋默认值。但是这个nginx缩放模块默认值不是空,而是“-”,官方文档只写了一边可以填“-”,但是两个边都填“-”也是支持的。
官方文档部分:
crop width height
proportionally reduces an image to the larger side size and crops extraneous edges by another side. To reduce by only one dimension, another dimension can be specified as “-”. In case of an error, the server will return code 415 (Unsupported Media Type). Parameter values can contain variables. When used along with the rotate parameter, the rotation happens beforereduction.