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