Nginx--proxy cache使用
項目中採用Nginx做爲代理服務器,靜態接口的數據都緩存在nginx中,這樣能夠有效減少源服務器的負載。在這裏整理一下Nginx proxy cache的配置。nginx
nginx proxy cache 原理
proxy_temp_path /data/nginx_cache/proxy_cache/proxy_temp_dir; proxy_cache_path /dev/shm/proxy_cache_dir levels=1:2 keys_zone=cache_one:200m inactive=2d max_size=2g; proxy_cache_use_stale error timeout invalid_header updating http_500 http_502 http_503 http_504 http_404;
location ^~ /static/ { ... ... #定製proxy_cache的key,去除imei和sn等個性化參數。 set $custom_proxy_cache_key $host$uri$is_args$args; include vhosts/customize_proxy_cache_key; #忽略Expires、Set-Cookie頭部 proxy_ignore_headers Expires Set-Cookie; proxy_cache cache_one; proxy_cache_valid 200 304 10m; proxy_cache_key $custom_proxy_cache_key; add_header X-Proxy-Cache $upstream_cache_status; expires 10m; ... ... }
這裏有幾個要注意的地方:瀏覽器
定製cache的key時,必定要注意:**謹慎使用值變化範圍比較大的參數**。由於,這裏使用參數的值做爲cache的key的,當值變化返回很大的時候,一方面會致使緩存文件變得很大,另外一方面緩存也就失去意義。
這裏有一個知識點:
源服務器是經過Set-Cookie來告訴瀏覽器cookie的信息,包括cookie值,path,以及域。只要瀏覽器查看請求知足本地cookie的域,就把這個cookie攜帶入頭部傳給server。這裏忽略掉這個頭部才能使nginx proxy_cache 生效。 緩存
上邊customize_proxy_cache_key具體配置以下:服務器
set $custom_params $query_string; #nginx緩存key去除imei if ( $custom_params ~ ^(.*)(&imei=[^&]+)(.*)$) { set $a $1; set $c $3; set $custom_params "${a}${c}"; } set $custom_proxy_cache_key $host$uri$is_args$custom_params;
這裏,就將參數中的imei和sn用戶惟一值的參數去除,保證cache健康。 cookie
配置完成後,重啓nginx,至此,nginx cache已經啓用。spa