HOW TO: Install and Configure Nginx FastCGI Cache on Ubuntu 20.04 via SSH

Object caching can significantly increase the efficiency of your WordPress site by reducing the process of accessing the database. However, there is still a lot of overhead when providing a page request because the server is necessary to parse PHP.

This overhead is generated by WordPress and PHP having to create the requested HTML page on each page load. We may lessen this strain on server resources by caching the HTML version of the requested page once it has been produced; then, on the next request for this page, we simply provide the cached HTML page and avoid calling WordPress or PHP entirely.

The following tutorial will show you how to set up Nginx FastCGI Cache on Ubuntu 20.04 LTS via SSH/CLI.

In this guide, we’ll use your_domain as an example domain name.

Example: sudo vi /var/www/nestormayagmajr

STEP 1: Edit Nginx Server Block /etc/nginx/sites-available/domain_name

sudo vi /etc/nginx/sites-available/your_domain

Copy and paste the following lines at line:1

# This config file uses nginx fastcgi-cache
fastcgi_cache_path /var/www/cache/your_domain-fastcgicache levels=1:2 keys_zone=your_domain:100m inactive=60m;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
log_format Sample-logs '[$time_local] $remote_addr $request_method $status $remote_user $request $http_host $http_referer [$http_user_agent] $upstream_response_time $request_time';

Under location ~ .php$, add the following FastCGI Configuration

#FastCGI CACHE Configuration
        fastcgi_cache your_domain;
        fastcgi_cache_valid 200 60m;
        fastcgi_cache_use_stale error timeout updating invalid_header http_500 http_503;
        fastcgi_cache_min_uses 1;
        fastcgi_cache_lock on;
        add_header X-FastCGI-Cache $upstream_cache_status;

Save and Quit.

:wq!

STEP 2: Test your NGINX Configuration

sudo nginx -t

Expected Output:

STEP 3: Restart your Nginx server for changes to take effect.

sudo systemctl restart nginx

STEP 4: Verify if the FastCGI Cache has been set up correctly.

Type the commands:

cd /var/www/cache

Check if there’s a directory:

ls

Expected output:

your_domain-fastcgicache

Other Verification Steps:

Use incognito > Go to your website, then open the DevTools.

Under Network, click your domain:

Go to Headers, then find the Response Headers:

You’ll notice that the X-FastCGI-Cache has been HIT. It means that the installation was successful.

Manually purge the cache:

sudo -i
cd /var/www/cache/sample_directory
rm -Rf sample_directory

Leave a Reply

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