zoukankan      html  css  js  c++  java
  • nginx配置image_filter生成缩略图

    最近有个需求,客户端向服务器请求图片时,可以带get参数请求想要的缩略图,例如http://www.xxxxx.com/Upload/img//1de23275134663.jpg?size=100x100;

    刚开始想法是用php的图片类来处理,在客服端请求图片时,nginx上用正则判断url是否请求缩略图的形式,如果是则rewrite到接口去处理生成缩略图;

    后来在谷歌看了一些相关文档后,其实可以用nginx的的 image_filter模块来处理;如果nginx上没有安装该模块的,可以谷歌看下攻略进行安装。

    首先要做的是用正则去匹配url为图片请求的并带有缩略图参数的才能走进区间。

    第一个注意的是由于location只匹配URI,不可以匹配get参数,所以?号就不能匹配了,就把?换成!,这样才能精准的去匹配,也就是客户端请求的url要为:

    http://www.xxxxx.com/Upload/img//1de23275134663.jpg!size=100x100;

    第二个注意的是Nginx不支持在if {} 这个 block 里面用 image_filter 函数,image_filter 的第一个参数 resize/crop 也不能用变量的方式传输。

    由于这条请求的文件是不存在的,所以需要处理后proxy到本机网址127.0.0.1 rewrite到正常请求url,所以需要在配置文件增加:
    server {
        listen 127.0.0.1:80;
        server_name 127.0.0.1;      
      
      
    # 正则匹配 location
    ~* ^(.*.(?:jpg|gif|png|jpeg|bmp))!{
        # 重写到正常的图片url rewrite
    ^(.*.(?:jpg|gif|png))! $1; } }

    image_filter具体配置如下:

    # 正则匹配 
    location ~* .(?:jpg|gif|png|jpeg|bmp)!size=(.*)$ {     # 设置变量来装$1 set $img_arg $1; if ($img_arg ~ "^(d+)x(d+)") { set $img_width $1; set $img_height $2; } if ($img_arg ~ "^(d+)$") { set $img_width $1; set $img_height "-"; }      if ($img_arg ~ "^x(d+)") { set $img_width "-"; set $img_height $1; } proxy_pass http://127.0.0.1:80;

    # 宽度与高度想使用图片原有参数,可设置为“-” image_filter crop $img_width $img_height; }

    基本配置已经完成,需要设置cache的可以通过参数去设置;有什么不足之处请各位大神指教,好了,电脑得还给包工头了,我得搬砖去了。

    参考文章:

    1.http://nginx.org/en/docs/http/ngx_http_image_filter_module.html

    2.https://www.centos.bz/2017/03/using-nginx-image_filter-resize-images/

    3.http://www.dnsdizhi.com/post-252.html

  • 相关阅读:
    119. Pascal's Triangle II
    118. Pascal's Triangle
    112. Path Sum
    111. Minimum Depth of Binary Tree
    110. Balanced Binary Tree
    108. Convert Sorted Array to Binary Search Tree
    88. Merge Sorted Array
    83. Remove Duplicates from Sorted List
    70. Climbing Stairs
    陌陌面试经历
  • 原文地址:https://www.cnblogs.com/boats/p/8399269.html
Copyright © 2011-2022 走看看