最新消息:

Nginx 缓存解决方案

未分类 admin 2562浏览 0评论

试验了用128MB的小机Nginx反代+缓存跑了个3万ip的站,负载一直在0.01-0.02,没感觉

目前,Nginx的缓存控制机制是软肋,特别是清理过期缓存方面,有2种方法来清理过期的缓存,当然,nginx自身也会清理的,但清理的机制不好。所以,只能do it yourself.

1. Cron 定时删除
下面是每2小时删除修改时间超过2天的文件

#clear cache pic
01 */2 * * * root find /path/to/your/site/ -type f -mtime +2 -print0 | xargs -0 -r rm >/dev/null 2>&1

2. Purge 方式触发删除

location / {
if ($request_method ~ “PURGE”){
rewrite (.*) /purge.php last;
}
add_header      X-Cache   HIT;
error_page      404 = @fetch;
}

location /purge.php {
internal;
fastcgi_pass   127.0.0.1:9000;
include        fastcgi_params;
fastcgi_param  SCRIPT_FILENAME    /www/21andy.com/fastcgi$fastcgi_script_name;
}

<?php
header(‘Cache-Control: max-age=0’);
$uri = $_SERVER[‘REQUEST_URI’];
$doc_root = $_SERVER[‘DOCUMENT_ROOT’];

$file = $doc_root.$uri;
echo $file.”n”;
if(is_file($file)) {
echo “File Clear…”;
@unlink($file);
} else {
echo “File Not Found…”;
}

也可以装插件 ngx_cache_purge
下载地下: http://wiki.nginx.org/NginxChsCachePurge

http {
proxy_cache_path  /tmp/cache  keys_zone=tmpcache:10m;

server {
location / {
proxy_pass         http://127.0.0.1:8000;
proxy_cache        tmpcache;
proxy_cache_key    $uri$is_args$args;
}

location ~ /purge(/.*) {
allow              127.0.0.1;
deny               all;
proxy_cache_purge  tmpcache $1$is_args$args;
}
}
}

注意,purge方式删除的话,由于nginx反代保存的是纯静态内容,我不想在反代的机子上装PHP
所以,应该由后端主动来触发完成
另外,由于是纯静态内容,很多以前直接用php的方式处理的东西,现在需要改成js+后端来处理了

详细不说了,思路就这样

BTW:

https://github.com/bummercloud/nginx-fastcgi-cache-purge

转载请注明:爱开源 » Nginx 缓存解决方案

您必须 登录 才能发表评论!