Nginx緩存
nginx有兩種緩存機制:fastcgi_cache和proxy_cache
下面我們來說說這兩種緩存機制的區別吧
proxy_cache作用是緩存后端服務器的內容,可能是任何內容,包括靜態的和動態的
fastcgi_cache作用是緩存fastcgi生成的內容,很多情況是php生成的動態內容
proxy_cache緩存減少了nginx與后端通信的次數,節省了傳輸時間和后端帶寬
fastcgi_cache緩存減少了nginx與php的通信次數,更減輕了php和數據庫的壓力。
proxy_cache緩存設置
復制代碼 代碼如下:
#注: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;
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;
}
}
fastcgi_cache緩存設置
復制代碼 代碼如下:
#定義緩存存放的文件夾
fastcgi_cache_path /tt/cache levels=1:2 keys_zone=NAME:2880m inactive=2d max_size=10G;
#定義緩存不同的url請求
fastcgi_cache_key "$scheme$request_method$host$uri$arg_filename$arg_x$arg_y";
server {
listen 8080;
server_name www.example .com;
location / {
root /www;
index index.html index.htm index.php;
}
location ~ (|.php)$ {
root /www;
fastcgi_pass 127.0.0.1:9000;
fastcgi_cache NAME;
fastcgi_cache_valid 200 48h;
fastcgi_cache_min_uses 1;
fastcgi_cache_use_stale error timeout invalid_header http_500;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
新聞熱點
疑難解答