云上的天涯

导航

Nginx缓存配置以及nginx ngx_cache_purge模块的使用

web缓存位于内容源Web服务器和客户端之间,当用户访问一个URL时,Web缓存服务器会去后端Web源服务器取回要输出的内容,然后,当下一个请求到来时,如果访问的是相同的URL,Web缓存服务器直接输出内容给客户端,而不是向源服务器再次发送请求.Web缓存降低了内容源Web服务器,数据库的负载,减少了网络延迟,提高了用户访问的响应速度,增强了用户体验.

web缓存服务器中,最著名的要数Squid Cache(简称为Squid),Squid是一个流浪的自由软件的代理服务器和Web缓存服务器。
----------------------------------------------------------------------------------------------------------------------------
Squid可以作为网页服务器的前置cache服务器缓存相关请求来提高Web服务器的速度;
Squid可以为一组人共享网络资源而缓存万维网,域名系统和其他网络搜索;
Squid可以通过过滤流量帮助网络安全,到局域网通过代理上网.
----------------------------------------------------------------------------------------------------------------------------
然而,当下多数公司网站的图片,js,css等文件的缓存会选择Nginx的web缓存服务。

如下将对nginx的web缓存功能的整体配置进行梳理性记录:
Nginx的Web缓存服务主要由proxy_cache相关指令集和fastcgi_cache相关指令集构成。
1)proxy_cache相关指令集用于反向代理时,对后端内容源服务器进行缓存.Nginx的proxy_cache缓存功能,十分稳定,速度不逊于Squid!

2)fastcgi相关指令集主要用于对FastCGI的动态程序进行缓存.两者功能基本一样.在功能上,Nginx已经具备Squid所拥有的Web缓存加速功能,清除指定URL缓存功能.而在性能上,Nginx对多核CPU的利用,胜过Squid不少.另外,在反向代理,负载均衡,健康检查,后端服务器故障转移,重写,易用性上,Nginx也比Squid强大很多.这使得一台Nginx可以同时作为"负载均衡服务器"与"Web缓存服务器"来使用.

proxy_cache相关指令集
(1)proxy_cache指令 
语法: proxy_cache zone_name ;
该指令用于设置哪个缓存区将被使用,zone_name的值为proxy_cache_path指令创建的缓存区的名称.

(2)proxy_cache_path指令
语法 proxy_cache_path path [levels=number]

keys_zone=zone_name:zone_size[inactive=time] [max_size=size];
该指令用于设置缓存文件的存放路径.

例如:
proxy_cache_path /usr/local/nginx/proxy_cache_dir levels=1:2 keys_zone=cache_one:500m inactive=1d max_size=30g ;
解释:
path 表示存放目录
levels 表示指定该缓存空间有两层hash目录,第一层目录为1个字母,第二层目录为2个字母,
保存的文件名会类似/usr/local/nginx/proxy_cache_dir/c/29/XXXXXX ;
keys_zone参数用来为这个缓存区起名.
500m 指内存缓存空间大小为500MB
inactive的1d指如果缓存数据在1天内没有被访问,将被删除。相当于expires过期时间的配置;
max_size的30g是指硬盘缓存空间为30G

(3)proxy_cache_methods指令 
语法:proxy_cache_methods[GET HEAD POST];
该指令用于设置缓存哪些HTTP方法,默认缓存HTTP GET/HEAD方法,不缓存HTTP POST 方法

(4)proxy_cache_min_uses指令 
语法:proxy_cache_min_uses the_number
该指令用于设置缓存的最小使用次数,默认值为1

(5)proxy_cache_valid指令 
语法: proxy_cache_valid reply_code [reply_code...] time ;
该指令用于对不同返回状态码的URL设置不同的缓存时间.
例如:
proxy_cache_valid 200 302 10m ;
proxy_cache_valid 404 1m ;
设置200,302状态的URL缓存10分钟,404状态的URL缓存1分钟.

(6)proxy_cache_key指令 
语法: proxy_cache_key line ;
该指令用来设置Web缓存的Key值,Nginx根据Key值md5哈希存储缓存.一般根据$host(域名),$request_uri(请求的路径)等变量组合成proxy_cache_key .

 

proxy_cache缓存配置的完整示例(多数nginx缓存的配置):
1)下载nginx和第三方的ngx_cache_purge模块的编译安装包(官网:http://labs.frickle.com/nginx_ngx_cache_purge/),将ngx_cache_purge编译到到Nginx中,用来清除指定URL的缓存
[root@test-huanqiu ~]# yum install -y pcre pcre-devel openssl openssl-devel gcc            //首先安装依赖
[root@test-huanqiu ~]# cd /usr/local/src 
[root@test-huanqiu src]# wget http://labs.frickle.com/files/ngx_cache_purge-2.3.tar.gz
[root@test-huanqiu src]# wget http://nginx.org/download/nginx-1.8.0.tar.gz
[root@test-huanqiu src]# tar -zxvf ngx_cache_purge-2.3.tar.gz
[root@test-huanqiu src]# tar zxvf nginx-1.8.0.tar.gz
[root@test-huanqiu src]# cd nginx-1.8.0.tar.gz
[root@test-huanqiu nginx-1.8.0]# ./configure --user=www --group=www --add-module=../ngx_cache_purge-2.3 --prefix=/usr/local/nginx --with-http_ssl_module --with-http_flv_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre 
[root@test-huanqiu src]# make && make install

此时启动nginx的话会看到新增了两个进程:

 

2)接着,在同一分区下创建两个缓存目录,分别供proxy_temp_path , proxy_cache_path指令设置缓存路径.
注意:两个指定设置的缓存路径必须为同一磁盘分区,不能跨分区.
[root@test-huanqiu src]# mkdir -p /usr/local/nginx/proxy_temp_path
[root@test-huanqiu src]# mkdir -p /usr/local/nginx/proxy_cache_path

3)在配置文件nginx.conf中对扩展名为gif,jpg,jpeg,png,bmp,swf,js,css的图片,flash,javascript , css文件开启Web缓存,其他文件不缓存。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
[root@test-huanqiu src]# vim /usr/local/nginx/conf/nginx.conf
user  www;
worker_processes  8;
  
events {
    worker_connections  65535;
}
  
http {
    include       mime.types;
    default_type  application/octet-stream;
    charset utf-8;
 
    log_format  main  '$http_x_forwarded_for $remote_addr $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_cookie" $host $request_time';
    sendfile       on;
    tcp_nopush     on;
    tcp_nodelay    on;
    keepalive_timeout  65;
 
#要想开启nginx的缓存功能,需要添加此处的两行内容!
#设置Web缓存区名称为cache_one,内存缓存空间大小为500M,缓存的数据超过1天没有被访问就自动清除;访问的缓存数据,硬盘缓存空间大小为30G
  proxy_cache_path /usr/local/nginx/proxy_cache_path levels=1:2 keys_zone=cache_one:500m inactive=1d max_size=30g;
 
#创建缓存的时候可能生成一些临时文件存放的位置
  proxy_temp_path /usr/local/nginx/proxy_temp_path;
 
    fastcgi_connect_timeout 3000;
    fastcgi_send_timeout 3000;
    fastcgi_read_timeout 3000;
    fastcgi_buffer_size 256k;
    fastcgi_buffers 8 256k;
    fastcgi_busy_buffers_size 256k;
    fastcgi_temp_file_write_size 256k;
    fastcgi_intercept_errors on;
  
     
    client_header_timeout 600s;
    client_body_timeout 600s;
  
    client_max_body_size 100m;             
    client_body_buffer_size 256k;           
  
    gzip  on;
    gzip_min_length  1k;
    gzip_buffers     4 16k;
    gzip_http_version 1.1;
    gzip_comp_level 9;
    gzip_types       text/plain application/x-javascript text/css application/xml text/javascript application/x-httpd-php;
    gzip_vary on;
  
 
    include vhosts/*.conf;
}

[root@test-huanqiu src]# ulimit -n 65535
[root@test-huanqiu src]# mkdir /usr/local/nginx/conf/vhosts
[root@test-huanqiu src]# vim /usr/local/nginx/conf/vhosts/wang.conf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
upstream LB-WWW {
      ip_hash;
      server 192.168.1.101:80 max_fails=3 fail_timeout=30s;     #max_fails = 3 为允许失败的次数,默认值为1
      server 192.168.1.102:80 max_fails=3 fail_timeout=30s;     #fail_timeout = 30s 当max_fails次失败后,暂停将请求分发到该后端服务器的时间
      server 192.168.1.118:80 max_fails=3 fail_timeout=30s;
    }
  
  
server {
     listen       80;
     server_name  www.wangshibo.com;
     index index.html index.php index.htm;
     root /var/www/html;
 
     access_log  /usr/local/nginx/logs/www-access.log main;
     error_log  /usr/local/nginx/logs/www-error.log;
 
     location / {
         proxy_pass http://LB-WWW;
         proxy_redirect off ;
         proxy_set_header Host $host;
         proxy_set_header X-Real-IP $remote_addr;
         proxy_set_header REMOTE-HOST $remote_addr;
         proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
         proxy_connect_timeout 300;             #跟后端服务器连接超时时间,发起握手等候响应时间
         proxy_send_timeout 300;                #后端服务器回传时间,就是在规定时间内后端服务器必须传完所有数据
         proxy_read_timeout 600;                #连接成功后等待后端服务器的响应时间,已经进入后端的排队之中等候处理
         proxy_buffer_size 256k;                #代理请求缓冲区,会保存用户的头信息以供nginx进行处理
         proxy_buffers 4 256k;                  #同上,告诉nginx保存单个用几个buffer最大用多少空间
         proxy_busy_buffers_size 256k;          #如果系统很忙时候可以申请最大的proxy_buffers
         proxy_temp_file_write_size 256k;       #proxy缓存临时文件的大小
         proxy_next_upstream error timeout invalid_header http_500 http_503 http_404;
         proxy_max_temp_file_size 128m;
        }
 
     location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|js|css)$ {         
      #使用Web缓存区cache_one,已在nginx.conf的缓存配置中命名的。
      proxy_cache cache_one ;
      #对不同HTTP状态码缓存设置不同的缓存时间
      proxy_cache_valid 200 304 12h ;
      proxy_cache_valid 301 302 1m ;
      proxy_cache_valid any 1m ;
      #设置Web缓存的Key值,Nginx根据Key值md5哈希存储缓存,这里根据"域名,URI,
      #参数"组合成Key
      proxy_cache_key $host$uri$is_args$args;
     }
  
    #用于清除缓存的url设置
    #假设一个URL为http://www.wangshibo.com/test.gif,那么就可以通过访问http://www.wangshibo.com/purge/test.gif清除该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 ;
    }
 
}

fastcgi_cache相关指令集
(1)fastcgi_cache指令
语法:fastcgi_cache zone_name;
该指令用于设置哪个缓存区将被使用,zone_name的值为fastcgi_cache_path指令创建的缓存区名称.

(2)fastcgi_cache_path指令
语法:fastcgi_cache_path path [levels=number] keys_zone=zone_name:zone_size [inactive=time] [max_size=size];
该指令用于设置缓存文件的存放路径,
例如:
fastcgi_cache_path /usr/local/nginx/fastcgi_cache_dir levels=1:2 keys_zone=cache_one:500m inactive=1d max_size=30g ;
注意这个指令只能在http标签内配置,
levels指定该缓存空间有两层hash目录,第一层目录为1个字母,第二层为2个字母,保存的
文件名会类似/usr/local/nginx/fastcgi_cache_dir/c/29/XXXX;
keys_zone参数用来为这个缓存区起名,
500m指内存缓存空间大小为500MB;
inactive的1d指如果缓存数据在1天内没有被访问,将被删除;
max_size的30g是指硬盘缓存空间为30GB

(3)fastcgi_cache_methods指令
语法:fastcgi_cache_methods [GET HEAD POST] ;
该指令用于设置缓存哪些HTTP方法,默认缓存HTTP GET/HEAD 方法,不缓存HTTP POST方法

(4)fastcgi_cache_min_uses指令
语法:fastcgi_cache_min_uses the_number;
该指令用于设置缓存的最小使用次数,默认值为1.

(5)fastcgi_cache_valid指令
fastcgi_cache_valid reply_code [reply_code...] time;
该‎指令用于对不同返回状态码的URL设置不同的缓存时间.
fastcgi_cache_valid 200 302 10m ;
fastcgi_cache_valid 404 1m ;
设置200,302状态的URL缓存10分钟,404状态的URL缓存1分钟.
如果不指定状态码,直接指定缓存时间,则只有200,301,302状态的URL缓存5分钟.

(6)fastcgi_cache_key指令
语法:fastcgi_cache_key line ;
该指令用来设置Web缓存的Key值,Nginx根据Key值md5哈希存储缓存.一般根据FastCGI服务器的地址和端口,$request_uri(请求的路径)等变量组合成fastcgi_cache_key。

fastcgi_cache缓存配置的完整示例
1)首先,在同一分区下创建两个缓存目录,分别供fastcgi_temp_path,fastcgi_cache_path指令设置缓存路径.
注意:两个指定设置的缓存路径必须为同一磁盘分区,不能跨分区.
[root@test-huanqiu src]# mkdir -p /usr/local/nginx/fastcgi_temp_path
[root@test-huanqiu src]# mkdir -p /usr/local/nginx/fastcgi_cache_path
2)配置文件nginx.conf对扩展名为gif,jpg,jpeg,png,bmp,swf,js,css的图片,Flash,JavaScript,CSS文件开启Web缓存,其他文件不缓存.

1
2
3
4
5
6
7
8
9
10
11
[root@test-huanqiu src]# vim /usr/local/nginx/conf/nginx.conf
........
http{
  #fastcgi_temp_path和fastcgi_cache_path指定的路径必须在同一分区
  fastcgi_temp_path /usr/local/nginx/fastcgi_temp_path ;
  #设置Web缓存区名称为cache_one,内存缓存空间大小为500MB,自动清除超过1天没有被
 
  #访问的缓存数据,硬盘缓存空间大小为30G
  fastcgi_cache_path /usr/local/nginx/fastcgi_cache_path levels=1:2 keys_zone=cache_one:200m inactive=1d max_size=30g ;
........
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
[root@test-huanqiu src]# vim /usr/local/nginx/conf/vhosts/wang.conf
  server{
  .......
     
    location ~ .*\.(php|php5)$ {
      #使用Web缓存区cache_one
      fastcgi_cache cache_one ;
      #对不同的HTTP状态码缓存设置不同的缓存时间
      fastcgi_cache_valid 200 10m ;
      fastcgi_cache_valid 301 302 1h ;
      fastcgi_cache_valid an 1m ;
      #设置Web缓存的key值,Nginx根据key值md5哈希存储缓存,这里根据"FastCGI服务 
 
    #器的IP,端口,请求的URI"组合成Key。
      fastcgi_cache_key 127.0.0.1:9000$requet_uri ;
      #FastCGI服务器
      fastcgi_pass 127.0.0.1:9000 ;
      fastcgi_index index.php ;
      include fcgi.conf ;
    }
}

 

-------------------------------------------------------------------------------------------------------------------------------------------------------------

 

我的个人示例主配置文件: 下面 $upstream_cache_status表示资源缓存的状态,有HIT MISS EXPIRED三种状态

复制代码

log_format access '$remote_addr,$http_x_forwarded_for,$remote_user,$time_local,$host,$request,$status,$request_uri,$http_referer,$reques t_time,$http_user_agent,$upstream_cache_status'; proxy_temp_path /usr/local/nginx110/proxy_temp_dir 1 2; proxy_cache_path /data/ifengsite/proxy_cache_dir/cache1 levels=1:2 keys_zone=cache1:200m inactive=1d max_size=100g;

        upstream houseservers {
        server 10.0.10.31:80 max_fails=3 fail_timeout=60 weight=1;
        server 10.0.10.32:80 max_fails=3 fail_timeout=60 weight=1;
        server 10.0.10.33:80 max_fails=3 fail_timeout=60 weight=1;

}

复制代码

server配置文件:注意purge的location需要处于被缓存的内容的location的前面,否则会被匹配拦截,无法准确匹配到purge!

复制代码
    location / {
         proxy_pass http://houseservers;
         proxy_set_header Host $host;
         proxy_set_header X-Real-IP $remote_addr;
    }

    location ~ /purge(/.*) {
         allow 127.0.0.1;
         allow 10.0.0.0/16;
         deny all;
         proxy_cache_purge cache1 $1$is_args$args;
   }

    location ~* \.(jpg|html|shtml)$ {
         proxy_pass http://houseservers;
proxy_set_header Host $host;
proxy_set_header X-Real_IP $remote_add; proxy_cache cache1; proxy_cache_key $uri$is_args$args; add_header X-Cache $upstream_cache_status; proxy_ignore_headers "Cache-Control" "Expires" "Set-Cookie";
expires 15d;
}
复制代码

 

这个缓存是把链接用md5编码hash后保存,所以它可以支持任意链接,同时也支持404/301/302这样的非200状态

查看你的nginx是根据什么作为key来hash的,我的设置是 proxy_cache_key $uri$is_args$args; 因此nginx会根据$uri$is_args$args作为key进行hash,因此可以模拟nginx对一个key进行再hash找到相应的文件路径,删除(具体可随意找个缓存文件 more 一下看看)

 

 

相关参考资料:http://www.cnblogs.com/Eivll0m/p/4921829.html

                   http://blog.csdn.net/czp11210/article/details/28596649

posted on 2017-04-29 11:36  云上的天涯  阅读(1390)  评论(0编辑  收藏  举报