1.配置文件
#注:proxy_temp_path和proxy_cache_path指定的路径必须在同一分区proxy_temp_path /web/tmp/nginx;#设置Web缓存区名称为cache_one,内存缓存空间大小为100MB,1天没有被访问的内容自动清除,硬盘缓存空间大小为1GB。proxy_cache_path /web/cache/nginx levels=1:2 keys_z>100m inactive=1d max_size=1g;
location / { #如果后端的服务器返回502、504、执行超时等错误,自动将请求转发到upstream负载均衡池中的另一台服务器,实现故障转移。 proxy_next_upstream http_502 http_504 error timeout invalid_header; proxy_cache cache_one; #对不同的HTTP状态码设置不同的缓存时间 proxy_cache_valid 2003041h; #以域名、URI、参数组合成Web缓存的Key值,Nginx根据Key值哈希,存储缓存内容到二级缓存目录内 proxy_cache_key $host$uri$is_args$args; proxy_pass http://webserver; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; }
反向代理的缓存功能是一个重定向,不是根据url生成缓存静态文件的功能
二.fastcgi模块缓存
1.配置文件
fastcgi_temp_path /web/tmp/fastcgi;#设置fastcgi缓存路径 levels代表目录层级,1:2会生成16*256,2:2会生成256*256 keys_zone代表缓冲区名称 inactive代表过期时间 max_size代表最多用多少磁盘空间fastcgi_cache_path /web/cache/fastcgi levels=1:2 keys_z>100m inactive=1d max_size=1g;
location~ [^/]\.php(/|$) { fastcgi_cache cache_two; fastcgi_cache_valid20010m; fastcgi_cache_methods GET HEAD; #忽视以下头信息fastcgi_ignore_headers"Cache-Control""Expires""Set-Cookie"; fastcgi_cache_key"$scheme$request_method$host$request_uri"; #添加状态头信息add_header X-Cache-CFC "$upstream_cache_status - $upstream_response_time"; fastcgi_index index.php; fastcgi_pass127.0.0.1:9000; include fastcgi_params; fastcgi_split_path_info ^(.+?\.php)(/.*)$; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param SCRIPT_NAME $fastcgi_script_name; fastcgi_param PATH_INFO $fastcgi_path_info; fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info; }
注意:
1.如果fastcgi响应的头信息里有Expires Cache-Control Set-Cookie的时候,fastcgi_cache是不起作用的,所以需要把fastcgi_ignore_headers这个配置项加上。
2.添加头信息X-Cache-CFC 是为了测试缓存是否起作用,$upstream_cache_status包含以下几个状态:
MISS 未命中,请求被传送到后端
HIT 缓存命中
EXPIRED 缓存已经过期请求被传送到后端
UPDATING 正在更新缓存,将使用旧的应答
STALE 后端将得到过期的应答
BYPASS 缓存被绕过了
三.参考
http://www.qttc.net/201307355.html
https://serversforhackers.com/nginx-caching/
http://www.ha97.com/5194.html
http://www.cnxct.com/several-reminder-in-nginx-fastcgi_cache-and-php-session_cache_limiter/
以上就介绍了Nginx系列(十四 nginx缓存),包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。