Nginx proxy_cache 使用示例
动态网站使用缓存是很有必要的。前段时间使用了 nginx proxy_stroe 来保存静态页面,以达到缓存的目的。当然 proxy stroe 用来做缓存是不够好的方案。
缓存这一块当然还有 squid 之类的独立缓存服务器。如果使用 nginx 为 web 服务器,还要加个 squid 来缓存,是觉得多了一个 http 请求层。幸好 nginx 0.7 有了 proxy_cache 来做这个缓存的事。
之前来有个 ncache 是新浪员工开发的 nginx 模块(好像只能在 nginx 0.6 中编译无运行)。已经停止维护了,已经被加到 nginx 标准库里了。昨天还不知道 proxy_cache 就是 ncache 的功能时,还在努力匹配 ncahce,浪费了N多时间,最终没看到可以缓存。后来尝试 proxy_cache 才解决,且使用简单。
nginx 0.7.65 默认安装就可以了。
安装好后开始匹配 proxy_cache,先准备后台服务器的文件,如是 time.jsp,内容:
1.
源码打印?
1.
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. }
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 后台返回的结果是 200 或 304 的响应,用 1m(分钟)的缓存。
proxy_cache_key 默认是 “$scheme$host$request_uri”。
proxy_cache_methods 默认是 GET HEAD。
当要缓存 post 请求后,要用 proxy_cache_methods POST 来打开。并且 proxy_cache_key 要对,post 的请求 query string 是在请求体内,所以加 $request_body 作为 key 的一部分。要用 post ,上面匹配去了注释就可以了。
2 comments so far
Leave a reply