Nginx ImageFilterModule 实践

image_filter 配合 proxy_pass && proxy_cache 动态切图。

server {
    listen 80; 
    server_name    img.doyoueat.com;

    location ~* ^/resize/w_(\d+)/h_(\d+)/(.*)$ {
        rewrite /resize/w_(\d+)/h_(\d+)/(.*)$ /$3?w=$1&h=$2 break;
        proxy_set_header Host  $host;
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header X-Forwarded-For  $proxy_add_x_forwarded_for;
        proxy_pass  http://127.0.0.1;
        proxy_cache cache_one;
        proxy_cache_valid  200 304 12h;
        proxy_cache_key $host$uri$is_args$args;
       add_header X-Cache "ImageCache Status: $upstream_cache_status";
    }   
    location ~* \.(jpg|png|gif)$ {   
        root /home/doyoueat/img/;
        if ($args ~ "w=([0-9]+)&h=([0-9]+)"){
            set $w $1; 
            set $h $2; 
        }   
        image_filter resize $w $h; 
    }   
}

###### 在 nginx.conf 添加proxy_cache配置 ####
      proxy_temp_path   /home/doyoueat/data/proxy_temp_dir;
      proxy_cache_path  /home/doyoueat/data/proxy_cache_dir  levels=1:2   keys_zone=cache_one:2m inactive=1d max_size=1g;

 

更优雅的写法:

server {
    listen 80;
    server_name    img.doyoueat.com;

    location ~* ^/resize/w_(\d+)/h_(\d+)/(.*)$ {
        proxy_pass  http://127.0.0.1/proc_img/$3?width=$1&height=$2;
        proxy_set_header Host  $host;
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header X-Forwarded-For  $proxy_add_x_forwarded_for;
        #proxy_cache cache_one;
        proxy_cache_valid  200 304 12h;
        proxy_cache_key $host$uri$is_args$args;
       add_header X-Cache "ImageCache Status: $upstream_cache_status";
    }   
    location /proc_img/{
        alias /home/doyoueat/img/;
        image_filter resize $arg_width $arg_height;
    }   
}   
 

 

访问: http://img.doyoueat.com/resize/w_150/h_155/3.jpg

响应头:

HTTP/1.1 200 OK
Server: nginx/0.8.53
Date: Sun, 27 Nov 2011 13:26:33 GMT
Content-Type: image/jpeg
Content-Length: 5913
Connection: keep-alive
Last-Modified: Sun, 27 Nov 2011 12:44:43 GMT
X-Cache: ImageCache Status:  HIT
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值