Apr 5, 2014

Server-level cache

We often use "plugins" like "WP Super Cache"... to have our contents using less server resources.
We also have to write various PHP-level code to having such functionality.

However, there is an alternative way to do it *automatically*, without having to repeatedly writing code to cache our content at PHP-level.

We care about 4 aspects of caching:
1-Where to cache (often files)
2-How long it cached (says 5 min or 30days, depend on how freshness the website)
3-Bypass for dynamic sections (login, admin, realtime...)
4-Clear cache

Assuming we using Nginx and passing request to backend PHP using socket, typically we having:

proxy_pass http://127.0.0.1:9000

We added something like:
http {
   proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=zone-a:8m max_size=1000m inactive=600m;
}
server {
  proxy_pass http://127.0.0.1:9000
  proxy_cache_key $proxy_host$request_uri$is_args$args;
  proxy_cache_valid 200 302 5m;
  proxy_cache zone-a;
}

proxy_cache_path defines place to put our cache data, naming "zone". We have control over its size, how to creating sub- directories (levels=1:2 )

proxy_cache specifies which zone to store cache.

proxy_cache_key define the pattern to cache. We may need to add how to know that the page is dynamic generated, such as cookie. Or we may use proxy_cache_bypass to tell, example, wp-admin will be bypassed.

set $wp_bypass 0;
if ($request_uri ~ "wp-admin") {
    set $wp_bypass 1;
}
proxy_cache_bypass $wp_bypass;
To clear cache, simply deletes files under zone directory!

Apache also having similar features, and if we need more flexible, a mature cache engine like Varnish may help us. Speed up and concentrate more on development!

No comments:

Post a Comment

New comment