標籤:lnmp
前言
Nginx是高效能的HTTP伺服器,通過Proxy Cache可以使其對靜態資源進行緩衝。其原理就是把靜態資源按照一定的規則存在本地硬碟,並且會在記憶體中緩衝常用的資源,從而加快靜態資源的響應。
配置Proxy Cache
以下為nginx配置片段:
proxy_temp_path /usr/local/nginx/proxy_temp_dir 1 2;#keys_zone=cache1:100m 表示這個zone名稱為cache1,分配的記憶體大小為100MB#/usr/local/nginx/proxy_cache_dir/cache1 表示cache1這個zone的檔案要存放的目錄#levels=1:2 表示緩衝目錄的第一級目錄是1個字元,第二級目錄是2個字元,即/usr/local/nginx/proxy_cache_dir/cache1/a/1b這種形式#inactive=1d 表示這個zone中的快取檔案如果在1天內都沒有被訪問,那麼檔案會被cache manager進程刪除掉#max_size=10g 表示這個zone的硬碟容量為10GBproxy_cache_path /usr/local/nginx/proxy_cache_dir/cache1 levels=1:2 keys_zone=cache1:100m inactive=1d max_size=10g;server { listen 80; server_name *.example.com; #在日誌格式中加入$upstream_cache_status log_format format1 ‘$remote_addr - $remote_user [$time_local] ‘ ‘"$request" $status $body_bytes_sent ‘ ‘"$http_referer" "$http_user_agent" $upstream_cache_status‘; access_log log/access.log fomat1; #$upstream_cache_status表示資源緩衝的狀態,有HIT MISS EXPIRED三種狀態 add_header X-Cache $upstream_cache_status; location ~ .(jpg|png|gif|css|js)$ { proxy_pass http://127.0.0.1:81; #設定資源緩衝的zone proxy_cache cache1; #設定緩衝的key proxy_cache_key $host$uri$is_args$args; #設定狀態代碼為200和304的響應可以進行緩衝,並且緩衝時間為10分鐘 proxy_cache_valid 200 304 10m; expires 30d; }}安裝Purge模組
Purge模組被用來清除緩衝
$ wget http://labs.frickle.com/files/ngx_cache_purge-1.2.tar.gz$ tar -zxvf ngx_cache_purge-1.2.tar.gz
查看編譯參數
$ /usr/local/nginx/sbin/nginx -V
在原有的編譯參數後面加上--add-module=/usr/local/ngx_cache_purge-1.2
$ ./configure --user=www --group=www --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module --with-http_realip_module --add-module=/usr/local/ngx_cache_purge-1.2$ make && make install
退出nginx,並重新啟動
$ /usr/local/nginx/sbin/nginx -s quit$ /usr/local/nginx/sbin/nginx
配置Purge
以下是nginx中的Purge配置片段
location ~ /purge(/.*) { #允許的IP allow 127.0.0.1; deny all; proxy_cache_purge cache1 $host$1$is_args$args;}清除緩衝
使用方式:
$ wget http://example.com/purge/uri
其中uri為靜態資源的URI,如果緩衝的資源的URL為 http://example.com/js/jquery.js,那麼訪問 http://example.com/purge/js/jquery.js則會清除緩衝。
命中率
儲存如下代碼為hit_rate.sh:
#!/bin/bash# author: Jeremy Wei <[email protected]># proxy_cache hit rateif [ $1x != x ] then if [ -e $1 ] then HIT=`cat $1 | grep HIT | wc -l` ALL=`cat $1 | wc -l` Hit_rate=`echo "scale=2;($HIT/$ALL)*100" | bc` echo "Hit rate=$Hit_rate%" else echo "$1 not exsist!" fielse echo "usage: ./hit_rate.sh file_path"fi
使用方式
$ ./hit_rate.sh /usr/local/nginx/log/access.log
本文出自 “Lonely(技術群:1991706)” 部落格,請務必保留此出處http://304076020.blog.51cto.com/7503470/1545246
利用Proxy Cache使Nginx對靜態資源進行緩衝