cache, php, web

Setup FastCGI caching in NGINX

Nginx allows to utilize FastCGI module which enables processing *.php files. When you serve site like this blog, caching may be useful tool, especially when you use small VPS server with not many resources. It also removes the need for using additional caching tools like Varnish.

Enable FastCGI cache

I assume your site is quite small, hence there is some configuration deliberately excluded. For more settings, reference the docs. For this example, configuration lies in separate file in /etc/nginx/sites-available/. If not, edit proper global config file.

Add the following lines outside of the server {} directive:

fastcgi_cache_path /etc/nginx/cache keys_zone=MYAPP:10m inactive=60m use_temp_path=off;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
add_header X-Cache $upstream_cache_status;

fastcgi_cache_path indicates where our cached pages will be stored, MYAPP is the name of zone name, inactive means that after 60 minutes cache will be invalidated, and use_temp_path=off avoids storing cache files in temp directory. It will save it straight to the destination folder. add_header will add X-Cache header to indicate if cache was used.

There is also a max size of cache, in this case :10m means 10 MB – it’s value must be greater than RAM + Swap. If exceeded, you will get an error Cannot allocate memory.

fastcgi_cache_key specifies how the cached file will be named, eg: Then it will be hashed with md5 and hash-named.

Next, inside location ~ .php$ { } where FastCGI configuration is, put:

fastcgi_cache MYAPP;
fastcgi_cache_valid 200 60m;

fastcgi_cache reference to the memory zone name which is specified above.

fastcgi_cache_valid indicates it will cache pages if response status is 200 for 60 minutes.

Apply changes

Check config

$ sudo nginx -t

If the result is:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

Restart nginx

sudo systemctl restart nginx

Test FastCGI caching

Go to your website. After first visit you should see in headers request x-cache as MISS, but when you refresh, page should be loaded much quickly with x-cache=HIT. Remember, NGINX reads cache-control header, and if it’s value is Private, No-Cache, or No-Store, it will not use cache. Set-Cookie also disables it. However, it can be ignored:

fastcgi_ignore_headers Cache-Control Set-Cookie;

That was the simplest configuration, more perks detailed in official docs.