一、說明
Nginx實現緩存功能
緩存數據分爲兩部分(索引,數據):
1、存儲數據的索引,存放在內存中;
2、存儲緩存數據,存放在磁盤空間中;
Nginx實現緩存是通過代理緩存pxory_cache
模塊
ngx_http_proxy_module模塊
常用的選項有
proxy_cache_path
說明
proxy_cache_path定義一個完整的緩存空間
指定緩存數據的磁盤路徑、索引存放的內存空間以及一些其他參數,如緩存刪除策略。
注意,該選項只能定義在http塊上下文中。
例
proxy_cache_path /data/cache levels=1:2 keys_zone=web:10m max_size=1G inactive=10;
緩存數據存儲在/data/cache目錄中;
選項
levels
配置在該目錄下再分兩層目錄,一層1個隨機字符作爲名稱,二層2個隨機字符作爲名稱,levels最多三層,每層最多兩個字符,這是爲了加快訪問文件的速度;最後使用代理url的哈希值作爲關鍵字與文件名,一個緩存數據如下:/data/nginx/cache/c/29/b7f54b2df7773722d382f4809d65029c;
keys_zone
用來爲這個緩存區起名,並設置大小。
指定名稱爲web,這個名稱後面proxy_cache需要引用
而10m就是內存空間的大小;
max_size
指定最大緩存數據磁盤空間的大小;
inactive
在inactive指定的時間內,未被訪問的緩存數據將從緩存中刪除。
proxy_cache
proxy_cache用來引用上面proxy_cache_path定義的緩存空間,現時打開緩存功能
例:
proxy_cache web; #引用上面定義上的緩存空間,同一緩存空間可以在幾個地方使用
proxy_cache_valid
proxy_cache_valid設置不同響應代碼的緩存時間
例
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
二、配置文件
三個步驟:新建緩存、打開緩存、緩存設置
如果要緩存整個頁面,需要在代碼中進行設置
/usr/local/tenginx/conf]$ cat nginx.conf
# For more information on configuration, see:
# * Official English Documentation: http://nginx.org/en/docs/
# * Official Russian Documentation: http://nginx.org/ru/docs/
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
# Load dynamic modules. See /usr/share/nginx/README.dynamic.
include ../modules/*.conf;
events {
worker_connections 1024;
}
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
include mime.types;
default_type application/octet-stream;
#新建緩存
proxy_cache_path /data/cache levels=1:2 keys_zone=nginx:20M max_size=2G inactive=5;
#爲緩存數據添加頭部信息
add_header muzigan-Cache "$upstream_cache_status form $server_addr";
upstream static_server {
server 192.168.17.175:80 weight=5;
server 192.168.17.176:80 weight=3;
check interval=3000 rise=2 fall=5 timeout=2000 type=http;
check_http_expect_alive http_2xx http_3xx;
}
server {
listen 80 default_server;
server_name _;
location ~ ^/images {
index index.php index.html;
proxy_pass http://static_server;
#開啓緩存
proxy_cache nginx;
#緩存設置
proxy_cache_valid 200 301 302 2m;
}
}
}