原文出處:http://blog.chenlb.com/2010/04/nginx-proxy-cache.html

動態(tài)網(wǎng)站使用緩存是很有必要的。前段時間使用了 nginx proxy_stroe 來保存靜態(tài)頁面,以達到緩存的目的。當然 proxy stroe 用來做緩存是不夠好的方案。

緩存這一塊當然還有 squid 之類的獨立緩存服務(wù)器。如果使用 nginx 為 web 服務(wù)器,還要加個 squid 來緩存,是覺得多了一個 http 請求層。幸好 nginx 0.7 有了 proxy_cache 來做這個緩存的事。

之前來有個 ncache 是新浪員工開發(fā)的 nginx 模塊(好像只能在 nginx 0.6 中編譯無運行)。已經(jīng)停止維護了,已經(jīng)被加到 nginx 標準庫里了。昨天還不知道 proxy_cache 就是 ncache 的功能時,還在努力匹配 ncahce,浪費了N多時間,最終沒看到可以緩存。后來嘗試 proxy_cache 才解決,且使用簡單。

安裝 Nginx 請看:安裝 Nginx 配置負載均衡,如果沒有 pcre 庫,可以到http://sourceforge.net/projects/pcre/files/ 下載(我用的是 8.02)。

nginx 0.7.65 默認安裝就可以了。

安裝好后開始匹配 proxy_cache,先準備后臺服務(wù)器的文件,如是 time.jsp,內(nèi)容:

  1. <%=new java.util.Date() %>  

conf/nginx.conf:

  1. user  nobody;  
  2. worker_processes  1;  
  3. error_log  logs/error.log;  
  4. pid        logs/nginx.pid;  
  5.   
  6. events {  
  7.     worker_connections  1024;  
  8.     use epoll;  
  9. }  
  10.   
  11. http {  
  12.     include       mime.types;  
  13.     default_type  application/octet-stream;  
  14.   
  15.     log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '  
  16.                       '$status $body_bytes_sent "$http_referer" "$request_body" '  
  17.                       '"$http_user_agent" "$http_x_forwarded_for" "$request_time"';  
  18.   
  19.     sendfile        on;  
  20.     keepalive_timeout  60;  
  21.   
  22.     proxy_cache_path /var/cache0 levels=1:2 keys_zone=pnc:100m inactive=2h max_size=10g;  
  23.     upstream backend {  
  24.         server 192.168.1.2:8080  weight=6;  
  25.         #server 192.168.1.3:8080  weight=4;  
  26.     }  
  27.   
  28.     server {  
  29.         listen       80;  
  30.         server_name  localhost;  
  31.   
  32.         access_log  logs/access.80.log  main;  
  33.   
  34.         location / {  
  35.             proxy_cache pnc;  
  36.             proxy_temp_path /var/nginx_temp;  
  37.             #proxy_cache_key "$request_uri$request_body";  
  38.             #proxy_cache_methods GET POST;  
  39.             proxy_cache_valid 200 304 1m;  
  40.             proxy_pass http://backend;  
  41.         }  
  42.   
  43.         error_page   500 502 503 504  /50x.html;  
  44.         location = /50x.html {  
  45.             root   html;  
  46.         }  
  47.     }  
  48. }  

啟動 nginx 后,打開瀏覽器,可以狂刷 Ctrl + F5,可以看到一樣的頁面。一分鐘后再會一個新的頁面。

是 proxy_cache_valid 200 304 1m; 告訴 nginx 后臺返回的結(jié)果是 200 或 304 的響應(yīng),用 1m(分鐘)的緩存。

proxy_cache_key 默認是 "$scheme$host$request_uri"。

proxy_cache_methods 默認是 GET HEAD。

當要緩存 post 請求后,要用 proxy_cache_methods POST 來打開。并且 proxy_cache_key 要對,post 的請求 query string 是在請求體內(nèi),所以加 $request_body 作為 key 的一部分。要用 post ,上面匹配去了注釋就可以了。

這些匹配指令詳情請看官方:http://wiki.nginx.org/NginxHttpProxyModule,中文版:http://wiki.nginx.org/NginxChsHttpProxyModule