[文章作者:张宴 本文版本:v1.2 最后修改:2009.01.12 转载请注明原文链接:http://blog.zyan.cc/nginx_cache/]

  Nginx从0.7.48版本开始,支持了类似Squid的缓存功能。这个缓存是把URL及相关组合当作Key,用md5编码哈希后保存在硬盘上,所以它可以支持任意URL链接,同时也支持404/301/302这样的非200状态码。虽然目前官方的Nginx Web缓存服务只能为指定URL或状态码设置过期时间,不支持类似Squid的PURGE指令,手动清除指定缓存页面,但是,通过一个第三方的Nginx模块,可以清除指定URL的缓存。

  Nginx的Web缓存服务主要由proxy_cache相关指令集和fastcgi_cache相关指令集构成,前者用于反向代理时,对后端内容源服务器进行缓存,后者主要用于对FastCGI的动态程序进行缓存。两者的功能基本上一样。

  最新的Nginx 0.8.32版本,proxy_cache和fastcgi_cache已经比较完善,加上第三方的ngx_cache_purge模块(用于清除指定URL的缓存),已经可以完全取代Squid。我们已经在生产环境使用了 Nginx 的 proxy_cache 缓存功能超过两个月,十分稳定,速度不逊于 Squid。

  在功能上,Nginx已经具备Squid所拥有的Web缓存加速功能、清除指定URL缓存的功能。而在性能上,Nginx对多核CPU的利用,胜过Squid不少。另外,在反向代理、负载均衡、健康检查、后端服务器故障转移、Rewrite重写、易用性上,Nginx也比Squid强大得多。这使得一台Nginx可以同时作为“负载均衡服务器”与“Web缓存服务器”来使用。
  


  1、Nginx 负载均衡与缓存服务器在 Linux 下的编译安装:
ulimit -SHn 65535
wget ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-8.00.tar.gz
tar zxvf pcre-8.00.tar.gz
cd pcre-8.00/
./configure
make && make install
cd ../

wget http://labs.frickle.com/files/ngx_cache_purge-1.0.tar.gz
tar zxvf ngx_cache_purge-1.0.tar.gz

wget http://nginx.org/download/nginx-0.8.32.tar.gz
tar zxvf nginx-0.8.32.tar.gz
cd nginx-0.8.32/
./configure --user=www --group=www --add-module=../ngx_cache_purge-1.0 --prefix=/usr/local/webserver/nginx --with-http_stub_status_module --with-http_ssl_module
make && make install
cd ../



  2、/usr/local/webserver/nginx/conf/nginx.conf 配置文件内容如下:
user  www www;

worker_processes 8;

error_log  /usr/local/webserver/nginx/logs/nginx_error.log  crit;

pid        /usr/local/webserver/nginx/nginx.pid;

#Specifies the value for maximum file descriptors that can be opened by this process.
worker_rlimit_nofile 65535;

events
{
  use epoll;
  worker_connections 65535;
}

http
{
  include       mime.types;
  default_type  application/octet-stream;

  charset  utf-8;
      
  server_names_hash_bucket_size 128;
  client_header_buffer_size 32k;
  large_client_header_buffers 4 32k;
  client_max_body_size 300m;
      
  sendfile on;
  tcp_nopush     on;

  keepalive_timeout 60;

  tcp_nodelay on;

  client_body_buffer_size  512k;
  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;

  gzip on;
  gzip_min_length  1k;
  gzip_buffers     4 16k;
  gzip_http_version 1.1;
  gzip_comp_level 2;
  gzip_types       text/plain application/x-javascript text/css application/xml;
  gzip_vary on;

  #注:proxy_temp_path和proxy_cache_path指定的路径必须在同一分区
  proxy_temp_path   /data0/proxy_temp_dir;
  #设置Web缓存区名称为cache_one,内存缓存空间大小为200MB,1天没有被访问的内容自动清除,硬盘缓存空间大小为30GB。
  proxy_cache_path  /data0/proxy_cache_dir  levels=1:2   keys_zone=cache_one:200m inactive=1d max_size=30g;
  
  upstream backend_server {
    server   192.168.8.43:80 weight=1 max_fails=2 fail_timeout=30s;
    server   192.168.8.44:80 weight=1 max_fails=2 fail_timeout=30s;
    server   192.168.8.45:80 weight=1 max_fails=2 fail_timeout=30s;
  }

  server
  {
    listen       80;
    server_name  www.yourdomain.com 192.168.8.42;
    index index.html index.htm;
    root  /data0/htdocs/www;  

    location /
    {
         #如果后端的服务器返回502、504、执行超时等错误,自动将请求转发到upstream负载均衡池中的另一台服务器,实现故障转移。
         proxy_next_upstream http_502 http_504 error timeout invalid_header;
         proxy_cache cache_one;
         #对不同的HTTP状态码设置不同的缓存时间
         proxy_cache_valid  200 304 12h;
         #以域名、URI、参数组合成Web缓存的Key值,Nginx根据Key值哈希,存储缓存内容到二级缓存目录内
         proxy_cache_key $host$uri$is_args$args;
         proxy_set_header Host  $host;
         proxy_set_header X-Forwarded-For  $remote_addr;
         proxy_pass http://backend_server;
         expires      1d;
    }
    
    #用于清除缓存,假设一个URL为http://192.168.8.42/test.txt,通过访问http://192.168.8.42/purge/test.txt就可以清除该URL的缓存。
    location ~ /purge(/.*)
    {
     #设置只允许指定的IP或IP段才可以清除URL缓存。
     allow            127.0.0.1;
     allow            192.168.0.0/16;
     deny            all;
     proxy_cache_purge    cache_one   $host$1$is_args$args;
    }    

    #扩展名以.php、.jsp、.cgi结尾的动态应用程序不缓存。
    location ~ .*\.(php|jsp|cgi)?$
    {
         proxy_set_header Host  $host;
         proxy_set_header X-Forwarded-For  $remote_addr;
         proxy_pass http://backend_server;
    }

    access_log  off;
  }
}



  3、启动 Nginx:
/usr/local/webserver/nginx/sbin/nginx




  4、清除指定的URL缓存示例:

  点击在新窗口中浏览此图片





技术大类 » Cache与存储 | 评论(99) | 引用(0) | 阅读(202842)
proxy Homepage
2011-4-24 18:10
很强大,学习了
dashan
2011-6-2 13:59
为什么我的nginx不能缓存? 在cache目录下没任何文件???
叶子
2011-7-6 16:32
看完后,我的问题和前面朋友提的问题差不多,我只有一台服务器,那么可否进行缓存图片操作,而不是采用你写的负载均衡到后端服务进行处理,前端进行缓存。
如果我只有一台对外如公网IP是192.168.1.22 ,域名如:主域名www.aaa.com  图片域名:img.aaa.com 那我怎么把img.aaa.com的图片做成缓存方式,或者说直接进行访问不用缓存来做效果是否也差不多。
server
  {
    listen       80;
    server_name  www.aaa.com;
    index index.html index.htm;
    root  /data0/htdocs/www;  
    location ~ .*\.php?$ {
      fastcgi_pass  127.0.0.1:9000;
      fastcgi_index index.php;
      include fcgi.conf;
    }
}
server
  {
    listen       80;
    server_name  img.aaa.com;
    index index.html;
    root  /data0/htdocs/img;  

    location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
    {
      expires      30d;
    }
}
wl
2011-9-20 18:43
请问用nginx proxy_cache来做缓存,能否统计缓存命中率,以及在htpp响应头里标记是否HIT或者MISS?
wl
2011-10-8 11:19
我想在nginx proxy服务器上配置:add_header up-rt $upstream_response_time; 以便在响应头中得到每个请求的上一级服务器的响应时间,结果在响应头中看到的不是0.235这样的时间值,而是1318043682这样的时间戳,但是将$upstream_response_time记如访问日志,却可以得到0.235这样的时间值,请问这是为什么?
wl
2011-10-12 19:59
用nginx proxy_cache 作缓存,返回命中的情况,好像是用$upstream_cache_status这个变量,对吧? MISS EXPIRED - expired, request was passed to backend UPDATING - expired, stale response was used due to proxy/fastcgi_cache_use_stale updating STALE - expired, stale response was used due to proxy/fastcgi_cache_use_stale HIT
louis vuitton uk Email Homepage
2011-11-22 17:11
This louis vuitton uk for sale belongs to the sounding just what are termed as Louis Vuitton vintage best sellers, many other products and services for the reason that range appearing companies.You will easily notice the unfold zippers of this coach outlet store online. That is the decoration. There are some inside pockets for you as well. They are easy to match your clothes and to carry.Let us inspire your inner beauty with fine christian louboutin sale. Purse the elegance in bridal wedding. Enjoy the fashion.
armani watches Email Homepage
2011-11-23 10:12
If you are looking for armani Bags, our armani watches Handbags Canada outlet store is your first choice. We promise Original Packing and Best Discount,3-5 Workdays To Your Door!If you buy bags and purses of the latest new designs from the louis vuitton outlet now, you can enjoy special discounts. What else are you waiting for?After you choose the right kind of plants and the size pot for the plant.
wedding520 Email Homepage
2011-12-27 15:58
ワイドネックライン、'V'ネックやボートネックラインは、一般にキャップスリーブとドレスのために選ばれている。ボートスタイルのネックラインと幅広いネックラインのためには、オフショルダーのキャップスリーブを追加することができます。オフショルダーのウエディングドレスは、数年以来、結婚式の摩耗で人気のパターンになっても流行で、今日でもあります。カラードレス 格安.のこのスタイルで素敵に見える模様のオフショルダーの袖に行く同じシースのサテンからステッチ/オフショルダーのキャップスリーブの上に薄いと飾ったときに裾フレアのビットとシースのサテンのイブニングドレスとスパゲッティネックラインがすごい見えます。
jinga50334 Email
2012-2-15 15:26
多谢张老师分享。我在做实验的时候发现,本地的缓存无法进行访问。不知道是什么原因。我搭的环境只能实现upstream 里面的冗余服务器的cache缓存。但是做缓存的服务器却实现不了
Michael Email
2012-2-20 14:20
windows下是否可以配置Nginx的proxy_cache缓存功能?请赐教,谢谢...
Hogan Email Homepage
2012-5-10 17:56
Ci sono diversi motivi principali per cui si può sicuramente trovare sul proprio volere le soluzioni contabili che coinvolgono tutta Stansted, anche se alcune persone potrebbero uomini e donne, probabilmente si dovrà disporre di soluzioni contabili rispetto con la gente. Stai con me per scoprire di più su molti dei motivi per prendere in considerazione l'impiego contabili in tutta Hogan Stansted. Costruire un businessIf vi capita di essere in funzione, è abbastanza possibile che si può fare uso di soluzioni contabili. Non date per scontato tutte le società hanno abbastanza soldi per utilizzare a tempo pieno il personale fiscali, così utilizzando una conditi insieme con l'agenzia affidabile che coinvolge tutta commercialisti Stansted potrebbe rendere meno difficili problemi.
hogan280 Email
2012-5-10 18:08
Focalizzando l'attenzione sull'elemento gara di questo reato - qualcosa suscitato dal comportamento oltraggioso della Difesa League inglese e BNP al di fuori del tribunale di Liverpool - è facile perdere di vista il fatto che Hogan questo è un racconto ampio di abuso e non è univoco ad una comunità. Marai Larasi, direttore della Imkaan e co-presidente del End Violence Against Women Coalition, avverte: "Una eccessiva attenzione su alcuni casi di sfruttamento sessuale con una concentrazione di etnie, piuttosto che lo sfruttamento della stessa è fuorviante e gli atteggiamenti razzisti dei combustibili che in ultima analisinon aiuta le donne e le ragazze. "
唐非糖 Email
2012-6-13 18:47
HI 你好:   根据你的配置,然后访问后并没有缓存下来,一般是什么原因,求解,谢谢!
dnsbed.com
2012-7-2 18:06
写得不错!!!!
yk
2012-10-24 18:01
怎么让proxy_cache 有条件缓存,条件在参数里???

谢谢
Coach Email Homepage
2012-11-3 14:49
"The Coach Outletengines that will likely power the J-31 we do know a bit mor.Coach Outlet  Those engines were actually revealed at the Zhuhai showCoach Outlet in 2008," Fisher said referring to an annual China air show. He beCoach Outletlieves the new J-31 engine is undergoing preliminary
zh_harry
2013-2-26 12:05
老大,proxy_cache写不进去内容啊。权限已经配置过了。救命啊!!!!
分页: 4/5 第一页 上页 1 2 3 4 5 下页 最后页
发表评论
表情
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
打开HTML
打开UBB
打开表情
隐藏
记住我
昵称   密码   游客无需密码
网址   电邮   [注册]