网站加速—fastcgi缓存的作用
之前已经介绍过异地的缓存加速,但是说实话解决根本问题才是硬道理。我的根本问题是wordpress的首页打开时间已经达到了7.77s这样的时间可不是很理想,标准互联网首页打开的极限时间是8s。
要想提高php的运算效率我想如下几点:
1.提高php进程数量
2.提高主机配置增加php处理速度
但是以上两点都依赖于更高级的主机配置。然而更高的配置意味着更高的消费。
那么开始我们的屌丝方法:
在nginx的配置文件http段落加入:
fastcgi_cache_path /var/cache/nginxfastcgi levels=1:2 keys_zone=fastcgicache:50m inactive=30m max_size=4g; fastcgi_cache_key $scheme$request_method$host$request_uri; fastcgi_cache_lock on; fastcgi_cache_use_stale error timeout invalid_header updating http_500; fastcgi_ignore_headers Cache-Control Expires Set-Cookie;
fastcgi_cache_path 声明cache路径,levels生成目录的模式这个比值越高可生成的散列目录越多。keys_zonekey名空间和名称后面使用的时候有用。inactive缓存有效时间这里的m是分钟。max_size最大缓存的尺寸避免写爆
fastcgi_cache_key 这里我用的参数输出大概就是blog.1117life.com/index.php?test这样的形式
fastcgi_cache_lock同时有请求处理的时候只有一个请求允许访问后端服务器,其余请求等待缓存结果再进行响应。
fastcgi_cache_stale 当发生错误,超时,无效的header等问题的时候需要请求后端服务器进行更新
fastcgi_ignore_headers 在响应的时候忽略一些header中的字符值的控制。
在server虚拟机配置中加入:
#cache control set $skip_cache 0; # POST requests and urls with a query string should always go to PHP if ($request_method = POST) { set $skip_cache 1; } if ($query_string != "") { set $skip_cache 1; } # Don't cache uris containing the following segments if ($request_uri ~* "/wp-admin/|/xmlrpc.php|wp-.*.php|/feed/|index.php|sitemap(_index)?.xml") { set $skip_cache 1; } # Don't use the cache for logged in users or recent commenters if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_no_cache|wordpress_logged_in") { set $skip_cache 1; }
这段指出在访问一些特定目录以及提交方法的时候不使用cache
最后在location ~ *\.php {} 中加入:
# note: adds a HTTP response header "X-Cache" returning HIT/MISS/BYPASS/EXPIRED for cache use status add_header X-Cache-CFC "$upstream_cache_status"; fastcgi_cache fastcgicache; fastcgi_cache_valid 200 302 1h; fastcgi_cache_min_uses 1; fastcgi_cache_bypass $skip_cache; fastcgi_no_cache $skip_cache;
add_header 在header中添加后端服务器cache的状态
fastcgi_cache 使用cache,后面的名称是cache的名称
fastcgi_cache_valid 在200和302情况下缓存1小时
fastcgi_cache_min_uses 最小cache的访问数量
fastcgi_cache_bypass fastcgi_no_cache 这里设置bypass(旁通)和不使用cache的情况下是符合$skip_cache也就是server主机段落中增加的哪些url是不cache的。
效果:
看看从7s多到达161ms感觉怎么样?
在测试的时候需要注意:
发现chrome进行测试的时候不稳定,经常会不使用cache,所以可以再用firefox验证一下
当然这里还有一个小问题,就是有了缓存固然好,缓存是1个小时如果1小时之内有文章修改过那非常抱歉只能等待1小时之后才会刷新,那么给大家一个手工刷新的办法,当然可能麻烦点需要重新编译nginx,cache_purge是个第三方模块因此需要如下操作:
wget http://labs.frickle.com/files/ngx_cache_purge-2.1.tar.gz tar xzfv ngx_cache_purge-2.1.tar.gz cd [nginx_Dir] ./configure --prefix=/usr/local/nginx --with-http_ssl_module --with-http_realip_module --with-http_gzip_static_module --with-http_stub_status_module --with-pcre --with-http_flv_module --with-http_image_filter_module --with-http_geoip_module --add-module=../ngx_cache_purge-2.1
然后在nginx配置文件server段中加入:
location ~ /purge(/.*) { fastcgi_cache_purge fastcgicache "$scheme$request_method$host$1"; }
还没说怎么清除呢,当然可以手工清除,不过最简单的办法就是在wordpress后台装上一个叫Nginx Helper的插件