FastCGI Caching with Nginx on VPS for WordPress

We assume that you have installed a LEMP server as per this tutorial and running WordPress websites in it.

Now, for caching wordpress sites, there are so many plugins available at wordpress plugin repository. But you know, the best plugin for caching sites on Nginx server is to use no plugin at all. Nginx has built in caching module which is called FastCGI. It is the best performer on LEMP stack.

Here we will show how to set up FastCGI Caching with Nginx on VPS for WordPress sites.

sudo nano /etc/nginx/sites-available/example.conf

Edit vhost file and the following lines at the top before server{} block:-

fastcgi_cache_path /var/run/nginx-cache levels=1:2 keys_zone=WORDPRESS:100m inactive=60m;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
fastcgi_cache_use_stale error timeout invalid_header http_500;
fastcgi_ignore_headers Cache-Control Expires Set-Cookie;

Now inside server{} block after server_name; line add the following code:-

set $skip_cache 1;

if ($request_method = POST) {
		set $skip_cache 1;
if ($query_string != "") {
		set $skip_cache 1;
if ($request_uri ~* "/wp-admin/|wp-.*.php|/feed/|sitemap.xml") {
		set $skip_cache 1;
if ($http_cookie ~* "comment_author|wordpress_no_cache|wordpress_logged_in") {
		set $skip_cache 1;

Now inside location ~ \.php$ {} block add this:

fastcgi_cache_bypass $skip_cache;
fastcgi_no_cache $skip_cache;
fastcgi_cache WORDPRESS;
fastcgi_cache_valid 200 60m;

Now restart Nginx server.

sudo service nginx restart

Now you should have a working caching engine.

To check it is working create a file named time.php in your site root folder.

sudo nano time.php

And add the following code:-


Now browse: Hit Refresh button again and again. If you see the same value it means caching is working fine.

Next you need to install a plugin Nginx-Helper to purge caching whenever a new post is created or an existing post is modified etc. automatically.

The Final example.conf will looks like: example.conf



Leave a Reply

Your email address will not be published. Required fields are marked *