jalxew
Last Updated: February 25, 2016
·
1.352K
· magnetikonline
Df1412e1775840374894798d5ed9a7ea

Utilizing Nginx's FastCGI cache

Something I wasn't aware of until recently, the Nginx FastCGI module comes with a rather nifty caching component.

Basically via config you are able to control the caching of responses from your FastCGI backend(s) (e.g. PHP-FPM) straight to disk, with the next request for the same cache key (which is typically made up of your $scheme, $request_method and $request_uri - but can be controlled) then served up from disk cache via Nginx directly.

I have posted some boilerplate config to a Gist here:

https://gist.github.com/magnetikonline/10450786

Things of note:

  • The target cache file path, shared memory size/use and GC timeout is set by fastcgi_cache_path
  • Cache key is controlled via fastcgi_cache_key and can include anything in it's makeup that's available in Nginx variable land.
  • Using a rewrite variable $fastcgi_skipcache and some if() conditions we can get quite complex as to what is in/out when it comes to adding content to the cache vs. passing through to your FastCGI backend.

Have had some really good success with this on a few highly trafficked, yet sluggish WordPress blogs of late with minimal code changes required within the apps themselves - including the use of custom HTTP headers with XMLHTTP requests and $http_[CUSTOM-HEADER] to control cache injection.

Well worth a look in.

Say Thanks
Respond

3 Responses
Add your response

14126
006a614ac35cb9de3dcd7206ac5e1b7a

Good read. How often does the cache get invalidated and or cleaned up? fastcgi_skipcache sounds like it could lead into a rabbit hole of support issues if it is used a lot. Is there any logging tool(s) for debugging the nginx cache?

over 1 year ago ·
14127
Df1412e1775840374894798d5ed9a7ea

Check the docs:

  • fastcgi_cache_valid controls cache time
  • debugging is/can be done with add_header X-Cache $upstream_cache_status; which will add a HIT/BYPASS HTTP header to responses.
  • The setup of fastcgi_skipcache is a job left to the reader, it's working great here but does require a good understanding of your application and/or usage patterns to get it right.
over 1 year ago ·
14132
006a614ac35cb9de3dcd7206ac5e1b7a

Great feedback. I haven't had a chance to even explore nginx caching so this is a great spot to dive in.

over 1 year ago ·