nginx代理做好了,緩存也配置好了,但是發現css、js、jpg這些靜態文件統統都cached成功。但是偏偏頁面文件依舊到源服務器取。
1. nginx不緩存原因
默認情況下,nginx是否緩存是由nginx緩存服務器與源服務器共同決定的, 緩存服務器需要嚴格遵守源服務器響應的header來決定是否緩存以及緩存的時常。header主要有如下:
Cache-control:no-cache、no-store
如果出現這兩值,nginx緩存服務器是絕對不會緩存的
Expires:1980-01-01
如果出現日期比當前時間早,也不會緩存。
2. 解決不緩存方案
2.1 方法一:
修改程序或者源服務器web程序響應的header
2.2 方法二:
nginx代理直接加上如下一句:
proxy_ignore_headers X-Accel-Expires Expires Cache-Control Set-Cookie;
3.緩存優先級
3.1架構圖
client端 <------------------> nginx cache <------------------>源服務器
經過大量測試發現:nginx的過期順序是有一個優先級的。下面首先說明各個影響緩存過期的因素:
(1)inactive:在proxy_cache_path配置項中進行配置,說明某個緩存在inactive指定的時間內如果不訪問,將會從緩存中刪除。
(2)源服務器php頁面中生成的響應頭中的Expires,生成語句為:
header("Expires: Fri, 07 Sep 2013 08:05:18 GMT");
(3)源服務器php頁面生成的max-age,生成語句為:
header("Cache-Control: max-age=60");
(4)nginx的配置項 proxy_cache_valid:配置nginx cache中的緩存文件的緩存時間,如果配置項為:proxy_cache_valid 200 304 2m;說明對于狀態為200和304的緩存文件的緩存時間是2分鐘,兩分鐘之后再訪問該緩存文件時,文件會過期,從而去源服務器重新取數據。
3.2其次對需要注意的一點:源服務器的expires和nginx cache的expires配置項的沖突進行說明,場景如下
(1)源服務器端有php文件ta1.php內容如下:
<?phpheader("Expires: Fri, 07 Sep 2013 08:05:18 GMT");header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");header("Cache-Control: max-age=60");echo "ta1";?>
(2)在nginx cache服務器端的配置信息如下:
…….proxy_cache_path /data0/proxy_cache_dir levels=1:2 keys_zone=cache_one:200m inactive=5s max_size=30g;…….. location ~ .*/.(php|jsp|cgi)${ proxy_read_timeout 10s; proxy_connect_timeout 10s; proxy_set_header Host $host; proxy_cache_use_stale updating; proxy_cache_key $host$uri$is_args$args; proxy_cache cache_one; #proxy_ignore_headers "Cache-Control"; #proxy_hide_header "Cache-Control"; #proxy_ignore_headers "Expires"; #proxy_hide_header "Expires"; proxy_hide_header "Set-Cookie"; proxy_ignore_headers "Set-Cookie"; #add_header Cache-Control max-age=60; add_header X-Cache '$upstream_cache_status from $server_addr'; proxy_cache_valid 200 304 2m; #proxy_cache_valid any 0m; proxy_pass http://backend_server; expires 30s;}………….
新聞熱點
疑難解答