Nginx FAST-CGI caching, and what it bought

Posted by LB on Sun, Jun 24, 2018

Background

In a classic LNMP stack, PHP-FPM parses every PHP script and Nginx forwards each PHP request to it. For a busy PHP site that puts a lot of pressure on PHP-FPM — so a FastCGI cache at the Nginx layer removes most of that pressure and improves response time, at the cost of serving slightly stale pages.

Nginx cache configuration

1. HTTP block

 1fastcgi_cache_path /tmp/cache/fastcgi_cache levels=1:2 keys_zone=fastcgi-cache:10m inactive=2d max_size=512m;
 2
 3fastcgi_cache_key $scheme$request_method$host$request_uri;
 4proxy_buffering on;
 5proxy_cache_valid any 10m;
 6proxy_temp_path /tmp/cache/tmp;
 7proxy_buffer_size 4k;
 8proxy_buffers 100 8k;
 9fastcgi_cache_lock on;
10fastcgi_cache_use_stale error timeout invalid_header updating http_500;
11fastcgi_ignore_headers Cache-Control Expires Set-Cookie;

keys_zone=fastcgi-cache is the zone the server block below refers to.

2. Server block

 1location ~ [^/]\.php(/|$)
 2{
 3  try_files $uri =404;
 4  fastcgi_pass  unix:/tmp/php-cgi.sock;
 5  fastcgi_index index.php;
 6  include fastcgi.conf;
 7  add_header PHP-Cache $upstream_cache_status;  # expose hit/miss
 8  fastcgi_cache fastcgi-cache;                  # use the zone
 9  fastcgi_cache_valid 200 60m;
10}

Results

For a site that does not need real-time freshness, enabling the cache clearly improves access speed. The map below is the nationwide test on this blog (17ce).

Test report