原文出處: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)容:
- <%=new java.util.Date() %>
conf/nginx.conf:
- user nobody;
- worker_processes 1;
- error_log logs/error.log;
- pid logs/nginx.pid;
-
- events {
- worker_connections 1024;
- use epoll;
- }
-
- http {
- include mime.types;
- default_type application/octet-stream;
-
- log_format main '$remote_addr - $remote_user [$time_local] "$request" '
- '$status $body_bytes_sent "$http_referer" "$request_body" '
- '"$http_user_agent" "$http_x_forwarded_for" "$request_time"';
-
- sendfile on;
- keepalive_timeout 60;
-
- proxy_cache_path /var/cache0 levels=1:2 keys_zone=pnc:100m inactive=2h max_size=10g;
- upstream backend {
- server 192.168.1.2:8080 weight=6;
- #server 192.168.1.3:8080 weight=4;
- }
-
- server {
- listen 80;
- server_name localhost;
-
- access_log logs/access.80.log main;
-
- location / {
- proxy_cache pnc;
- proxy_temp_path /var/nginx_temp;
- #proxy_cache_key "$request_uri$request_body";
- #proxy_cache_methods GET POST;
- proxy_cache_valid 200 304 1m;
- proxy_pass http://backend;
- }
-
- error_page 500 502 503 504 /50x.html;
- location = /50x.html {
- root html;
- }
- }
- }
啟動 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