ngx_cache_purge模塊的作用:用於清除指定url的緩存
1、編譯如下:
# ./configure --prefix=/app/nginx --with-http_stub_status_module --with-http_ssl_module --add-module=../ngx_cache_purge-2.3 # make # make install
2、nginx配置如下:
proxy_cache_path /app/proxy_cache_dir levels=1:2 keys_zone=cache1:200m inactive=1d max_size=10g; #設置Web緩存區名稱為cache1,內存緩存空間大小為200MB,1天沒有被訪問的內容自動清除,硬盤緩存空間大小為30GB。levels=1:2 表示緩存目錄的第一級目錄是1個字符,第二級目錄是2個字符,即/app/proxy_cache_dir/cache1/a/1b這種形式 server { listen 80; server_name localhost; #charset koi8-r; #access_log logs/host.access.log main; location / { root html; index index.html index.htm; } location ~ /purge(/.*) { allow 127.0.0.1; allow 192.168.116.0/24 deny all; proxy_cache_purge cache1 $host$1$is_args$args; } location ~ \.(gif|jpg|jpeg|png|bmp|ico)$ { proxy_set_header Host $host; proxy_set_header X-Forwarded-For $remote_addr; proxy_pass http://127.0.0.1:8080; proxy_cache cache1; #設置資源緩存的zone proxy_cache_key $host$uri$is_args$args; #設置緩存的key,以域名、URI、參數組合成Web緩存的Key值,Nginx根據Key值哈希,存儲緩存內容到二級緩存目錄內 proxy_cache_valid 200 304 12h; #對不同的HTTP狀態碼設置不同的緩存時間 expires 7d; #緩存時間 } #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } }
啟動nginx,查看進程,發現新增了兩個進程:
3、驗證緩存及手動清除指定url緩存功能
如果在緩存時間之類需要更新被緩存的靜態文件怎么辦呢,這時候就需要手動來清除緩存了。
訪問一張圖片:

查看緩存的文件:

更換圖片內容,然后清除緩存后再訪問:
http://192.168.116.130/purge/test/n.jpg #訪問此url可以清楚緩存。

再次訪問原來的url,圖片已更新:
