Nginx缓存

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

1、Nginx的Web缓存服务主要由 proxy_cache相关指令集 fastcgi_cache相关指令集 构成。
1)proxy_cache相关指令集用于反向代理时,对后端内容源服务器进行缓存.

2)fastcgi相关指令集主要用于对FastCGI的动态程序进行缓存.

 

proxy_cache相关指令集


(1)proxy_cache指令
语法: proxy_cache  zone_name ;

1、该指令用于设置 哪个缓存区将被使用,zone_name的值为proxy_cache_path指令创建的缓存区的名称。
2、proxy_pass 指定获取静态内容的地址.

(2)proxy_cache_path指令

该指令用于设置缓存文件的存放路径等相关信息.
语法

 

 proxy_cache_path path [levels=number] keys_zone=zone_name:zone_size[inactive=time] [max_size=size];
 1 例如:
 2 proxy_cache_path /usr/local/nginx/proxy_cache_dir levels=1:2 keys_zone=cache_one:500m inactive=1d max_size=30g ;
 3 解释:
 4 path 表示存放目录
 5 levels 表示指定该缓存空间有两层hash目录,第一层目录为1个字母,第二层目录为2个字母, 保存的文件名会类似/usr/local/nginx/proxy_cache_dir/c/29/XXXXXX ;
 6 keys_zone 参数用来为这个缓存区起名.
 7 500m  指内存缓存空间大小为500MB
 8 inactive 的1d指如果缓存数据在1天内没有被访问,将被删除。
 9 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            //首先安装依赖
groupadd www
useradd -s /sbin/nologin -g www www
[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

2)接着,在同一分区下创建两个缓存目录,分别供proxy_temp_path , proxy_cache_path指令设置缓存路径.
注意:proxy_temp_path和proxy_cache_path指定的路径必须在同一磁盘分区,决不能跨区分,因为它们之间是硬链接的关系,避免不通文件系统之间的磁盘IO消耗。

[root@test-huanqiu src]# mkdir -p /usr/local/nginx/proxy_cache_path             #注意,这两个目录的权限一定要是www.www,即是nginx进程权限
[root@test-huanqiu src]# mkdir -p /usr/local/nginx/proxy_temp_path               #这是缓存文件的临时存放目录
[root@localhost nginx-1.13.12]# chown www.www /usr/local/nginx/proxy_cache_path
[root@localhost nginx-1.13.12]# chown www.www /usr/local/nginx/proxy_temp_path

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

 

[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
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 ;
    }
 
}

 

 

nginx: [emerg] unknown log format "main" in /usr/local/nginx/conf/vhosts/wang.conf:15

 

解决方法:在http{}中找到下面的代码,取消注释。

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';

 如果缓存没有缓存到东西,有可能是location匹配不正确或者下面的指令没有添加。

      proxy_cache cache_one ;
      proxy_cache_valid 200 304 12h ;
      proxy_cache_valid 301 302 1m ;
      proxy_cache_valid any 1m ;
      proxy_cache_key $host$uri$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缓存,其他文件不缓存.

 

[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 ;
........
}
[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 ;
    }
}

ngx_cache_purge 是 nginx 的第三方那个模块,用于清除 FastCGI, proxy, SCGI and uWSGI 缓存,nginx默认安装就会带有反向代理的功能,但想要更好的使用,还得配备frickle.com的ngx_cache_purge模块,用于清除指定URL的缓存。
proxy_cache和fastcgi_cache构成了Nginx的缓存,proxy_cache主要用于反向代理时,对后端内容源服务器进行缓存,fastcgi_cache主要用于对FastCGI的动态程序进行缓存。两者的功能基本上一样。
-> proxy_cache的作用是缓存后端服务器的内容,可能是任何内容,包括静态的和动态。
-> proxy_cache缓存减少了nginx与后端通信的次数,节省了传输时间和后端宽带。
-> fastcgi_cache的作用是缓存fastcgi生成的内容,很多情况是php生成的动态的内容。
-> fastcgi_cache缓存减少了nginx与php的通信的次数。

根据业务部门需求,申请一台文件的cache服务器。如下记录在单台机器上部署Nginx缓存服务过程:
nginx缓存配置(缓存配置的参数这里就不做过多解释了,在前面的文档中已说明过,这里只做简单记录)
[root@storage01 ~]# cat /data/nginx/conf/nginx.conf|grep -v "^$"|grep -v "#"
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;
  
    proxy_temp_path /data/nginx/proxy_temp;
    proxy_cache_path /data/nginx/proxy_cache levels=1:2 keys_zone=cache_one:500m inactive=1d max_size=30g;
      
    client_header_timeout 600s;
    client_body_timeout 600s;
   
    client_max_body_size 50m;            
    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;
}
 
注意:缓存目录/proxy_cache和/proxy_temp一定要在同一个分区下,并且权限一定要和nginx程序权限一致(即要有写入权限,否则不能生产缓存文件)!
[root@storage01 ~]# mkdir /data/nginx/proxy_cache
[root@storage01 ~]# mkdir /data/nginx/proxy_temp
[root@storage01 ~]# chown -R www.www /data/nginx/proxy_cache
[root@storage01 ~]# chown -R www.www /data/nginx/proxy_temp
[root@storage01 ~]# chmod -R 777 /data/nginx/proxy_cache
[root@storage01 ~]# chmod -R 777 /data/nginx/proxy_temp
 
[root@storage01 ~]# cat /data/nginx/conf/vhosts/8888.conf
server {
     listen       8888;
     server_name  localhost;
 
     access_log  /data/nginx/logs/8888-access.log main;
     error_log  /data/nginx/logs/8888-error.log;
 
location / {
     index index.html index.htm;
     root /data/img/;
    }
}
 
[root@storage01 ~]# cat /data/nginx/conf/vhosts/img.conf
upstream cache {
      server localhost:8888 max_fails=3 fail_timeout=30s;
    }
 
server {
     listen       80;
     server_name  img.wang.com;
 
     access_log  /data/nginx/logs/img-access.log main;
     error_log  /data/nginx/logs/img-error.log;
 
     location / {
         proxy_pass http://cache;
         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_next_upstream error timeout invalid_header http_500 http_503 http_404;
 
         proxy_cache cache_one ;
         proxy_cache_valid 200 304 12h ;
         proxy_cache_valid 301 302 1m ;
         proxy_cache_valid any 1m ;
         proxy_cache_key $host$uri$is_args$args;
        }
   
    location ~ /purge(/.*) {
      allow all ;
      proxy_cache_purge cache_one $host$1$is_args$args ;
      error_page 405 =200 /purge$1;
    }
}

 访问域名测试

[root@storage01 ~]# ll -d /data/img/
drwxr-xr-x 3 www www 4096 Aug 21 14:56 /data/img/
[root@storage01 ~]# ll /data/img/
total 8
-rwxr-xr-x 1 www www   31 Aug 16 15:44 index.html
drwxr-xr-x 2 www www 4096 Aug 21 14:57 upload
[root@storage01 ~]# cat /data/img/index.html
缓存服务器!!!!!
[root@storage01 ~]# ll /data/img/upload/
total 140
-rw-r--r-- 1 www www 140935 Aug 17 09:31 test.jpg

 

查看缓存文件

 

groupadd nginx
useradd -s /sbin/nologin -g nginx nginx
[root@test-huanqiu src]# mkdir -p /usr/local/nginx/proxy_cache_path             #注意,这两个目录的权限一定要是www.www,即是nginx进程权限
[root@test-huanqiu src]# mkdir -p /usr/local/nginx/proxy_temp_path               #这是缓存文件的临时存放目录
[root@localhost nginx-1.13.12]# chown -R nginx.nginx /usr/local/nginx/proxy_cache_path
[root@localhost nginx-1.13.12]# chown -R nginx.nginx /usr/local/nginx/proxy_temp_path
[root@localhost nginx-1.13.12]# chmod 777 /usr/local/nginx/proxy_cache_path
[root@localhost nginx-1.13.12]# chmod 777 /usr/local/nginx/proxy_temp_path

 

user  nginx;
worker_processes  8;

events {
    worker_connections  65535;
}


http {
    include       mime.types;
    default_type  application/octet-stream;
    #charset utf-8;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    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';

    #access_log  logs/access.log  main;

    sendfile        on;
    tcp_nopush     on;
    tcp_nodelay    on;
    keepalive_timeout  65;
    
    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;
    #############################################
    #############################################
    
    server {
    listen 8088;
    server_name www.058.com;
    #charset koi8-r;
    ##access_log logs/host.access.log main;
    location / {
        proxy_pass http://www.51cto.com;  #指定被代理服务器的地址
        # 以下三行是缓存相关配置
        proxy_cache cache_one;
        proxy_cache_valid 200 1d;
        proxy_cache_use_stale error timeout invalid_header updating http_500 http_503 http_404;
        }
    error_page 500 502 503 504 /50x.html;
    
    }
#include vhosts/*.conf;
}

 

 

 

 

 

posted @ 2018-05-29 17:49  linuxws  阅读(2439)  评论(0编辑  收藏  举报