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

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM