原文地址:http://balzac.iteye.com/blog/2033783
1、步骤紧接第一弹。只是稍微在 nginx.conf 里添加了一点配置.
2、添加代码如下:
a、http标签内添加
##cache## proxy_connect_timeout 5; proxy_read_timeout 60; proxy_send_timeout 5; proxy_buffer_size 16k; proxy_buffers 4 64k; proxy_busy_buffers_size 128k; proxy_temp_file_write_size 128k; proxy_cache_key $host$server_port$request_uri; proxy_temp_path html/temp; proxy_cache_path html/cache/yy levels=1:2 keys_zone=yy:200m inactive=1d max_size=30g; ##end##
b、配置静态元素url
location ~ .*\.(gif|jpg|png|jpeg|bmp|css|js|flv|ico|swf|zip|html|htm|txt)(.*) { proxy_pass http://big_server_com; proxy_redirect off; proxy_set_header Host $host; proxy_cache yy; proxy_cache_valid 200 302 6h; proxy_cache_valid 301 1d; proxy_cache_valid any 1m; expires 30d; }
3、添加一行add_header X-Cache $upstream_cache_status 。添加位置如下图
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
add_header X-Cache $upstream_cache_status; #添加这行即可
4、测试。首次打开项目中的图片url时,打开Google Chrome浏览器开发工具,点击NETWORK选项。
首次输入 http://localhost/demo/photo/20140413/2147e26b7d5a45a5ba9a876dbc5a3234.jpg,
Cache-Control:max-age=120
Connection:keep-alive
Date:Sun, 13 Apr 2014 04:36:21 GMT
ETag:W/"384534-1397362175350"
Expires:Sun, 13 Apr 2014 04:38:21 GMT
Last-Modified:Sun, 13 Apr 2014 04:09:35 GMT
Server:nginx/1.4.6-win64
X-Cache:MISS
继续刷新看到
Cache-Control:max-age=120
Connection:keep-alive
Date:Sun, 13 Apr 2014 04:37:30 GMT
ETag:W/"384534-1397362175350"
Expires:Sun, 13 Apr 2014 04:39:30 GMT
Last-Modified:Sun, 13 Apr 2014 04:09:35 GMT
Server:nginx/1.4.6-win64
X-Cache:HIT
如果删除nginx下的缓存文件,刷新url,可看到:
Cache-Control:max-age=120
Connection:keep-alive
Date:Sun, 13 Apr 2014 04:38:55 GMT
ETag:W/"384534-1397362175350"
Expires:Sun, 13 Apr 2014 04:40:55 GMT
Last-Modified:Sun, 13 Apr 2014 04:09:35 GMT
Server:nginx/1.4.6-win64
X-Cache:MISS
至此,该图片缓存已配置成功。
ps:如有不对,欢迎批评指正。