How to Setup Nginx FastCGI Cache on Ubuntu 24.04, 22.04 or 20.04

This guide will demonstrate how to setup Nginx FastCGI Cache on Ubuntu 24.04, 22.04, or 20.04 Linux LTS releases using the command-line terminal and provide setup tips.

Nginx FastCGI Cache significantly enhances your website’s performance by reducing the processing load on your Ubuntu server. This caching solution is particularly effective for dynamic content, allowing Nginx to serve cached content directly without invoking PHP processors, thus speeding up the response time and reducing resource consumption. Let’s delve into the key features and benefits that make Nginx FastCGI Cache a vital tool for your web infrastructure:

  • Efficient Content Delivery: Nginx FastCGI Cache stores dynamic content output, enabling faster access and distribution.
  • Reduced Server Load: Serving cached content minimizes the number of PHP calls, lightening the server’s load.
  • Scalability: Nginx FastCGI Cache helps manage increased traffic without compromising speed as your website grows.
  • Customizable Caching: This option offers flexibility in setting cache expiration, bypass, and update conditions to fit your specific needs.
  • Improved User Experience: Faster website load times contribute to a better user experience, which can positively impact visitor retention and SEO rankings.
  • Resource Optimization: Optimizes the utilization of server resources, leading to more efficient handling of concurrent requests.
  • Easy Debugging: Provides straightforward mechanisms to debug and validate cached content, ensuring smooth operation.
  • Compatibility: Works seamlessly with popular CMS platforms, enhancing their performance without extensive configuration.

As we transition to the technical how-to, remember that implementing Nginx FastCGI Cache is a strategic move to boost your site’s efficiency and user satisfaction.

Now, let’s get started on enhancing your website’s performance with Nginx FastCGI Cache.

Setup Nginx FastCGI Cache on Ubuntu

Edit the Nginx Configuration File for FastCGI Cache

Open the Configuration File

First, you need to open the nginx.conf file. We will use the nano text editor, but you can use any text editor you are comfortable with. Enter this command:

sudo nano /etc/nginx/nginx.conf

Configure FastCGI Parameters

Inside the file, locate the HTTP block and add the following lines:

fastcgi_cache_path /var/nginx/fastcgi_cache levels=1:2 keys_zone=fcgicache:150m max_size=20g inactive=60m use_temp_path=off;
fastcgi_cache_key "$scheme$request_method$host$request_uri";

After entering the lines, press CTRL + O, type Y, and then press CTRL + X to exit.

Understand the FastCGI Parameters

  • fastcgi_cache_path: This parameter sets the location for storing the FastCGI cache (/var/nginx/fastcgi_cache). It is essential as it dictates where the cached content will reside.
  • levels=1:2: This creates a two-level directory hierarchy under your cache location. This design helps in spreading out files across two directories, which, in turn, reduces the risk of disk I/O bottlenecks.
  • keys_zone: It specifies the name of the shared memory zone (fcgicache) and its size (150M). The shared memory zone is crucial for storing cache keys and metadata.
  • max_size: This defines the maximum size of the cache (in this example, 20GB). When this limit is reached, the oldest files will be removed to make space for new ones.
  • inactive: This specifies the duration after which data not been accessed will be removed from the cache. In this example, it’s set to 60 minutes.
  • use_temp_path: Setting this to off instructs Nginx to write files directly to the specified cache folder, bypassing the use of a temporary storage area.
  • fastcgi_cache_key: It’s used to define the key for cache lookup. Nginx creates an MD5 hash of this key to use as the name of cache files.

Configure the Nginx Server Block for FastCGI Cache

Edit Server Block File

Next, you need to edit your server block file. For this example, we’ll assume the file is named example.com.conf. Open it with the following command:

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

Insert FastCGI Cache Directives

Assuming you have LEMP installed, insert the following lines inside the location block for PHP files:

fastcgi_cache fcgicache;
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;

Understand the FastCGI Cache Directives

  • fastcgi_cache: Enables caching and specifies the shared memory zone that was defined earlier.
  • fastcgi_cache_valid: Defines the cache duration for specific HTTP status codes.
  • fastcgi_cache_use_stale: Sets conditions under which Nginx can use a stale cached response.
  • fastcgi_cache_min_uses: Specifies how often a response must be requested before it gets cached.
  • fastcgi_cache_lock: Ensures that only one request at a time populates a new cache element, preventing a ‘cache stampede’.
  • add_header: Adds a custom header (X-FastCGI-Cache) to the HTTP response, indicating whether the response was served from the cache.

Configure FastCGI Cache Purge on Nginx

Setting Up Cache Purge

Cache purging allows you to remove content from the cache before it expires. To configure cache purging, create a cache purge directive by inserting the following lines in your server block file:

location ~ /purge(/.*) {
    # Uncomment the following two lines to allow purge only from the webserver
    allow 127.0.0.1;
    deny all;
    fastcgi_cache_purge fcgicache "$scheme$request_method$host$1";
}

Press CTRL + O, type Y, and then press CTRL + X to exit the text editor.

Alternative Approach for Cache Purging Issues

If you face issues with cache purging, you can adjust the cache expiry time instead. For medium to high-traffic websites, setting a lower expiry rate, such as 2 hours inactive and 4 hours for overall expiry, is often more efficient.

Test and Restart the Nginx Server

Test the Configuration

It’s essential to validate the Nginx configuration to avoid syntax errors or misconfigurations. Use the following command:

sudo nginx -t

You should see the following output if everything is correct:

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

Restart Nginx Server

Finally, restart the Nginx server to apply the changes you’ve made:

sudo systemctl restart nginx

Create and Optimize Nginx FastCGI Cache Directory on Ubuntu

Create FastCGI Cache Directory

Let’s now create the directory where Nginx will store the cache files. This path was specified earlier in the nginx.conf file:

sudo mkdir -p /var/nginx/fastcgi_cache

Optimize the Cache Directory with tmpfs (Optional)

If your system has sufficient RAM, you can opt to use tmpfs to store the cache in memory. This can result in faster access times compared to disk storage. However, be cautious, as storing in RAM can consume significant memory resources. Here’s how you can mount the cache directory as tmpfs:

Edit /etc/fstab file:

sudo nano /etc/fstab

Add the following line at the end of the file:

tmpfs   /var/nginx/fastcgi_cache   tmpfs   defaults,size=512M   0 0

This allocates 512MB of your RAM for the cache. You can adjust the size accordingly based on your system resources.

Mount the tmpfs:

sudo mount -a

This configuration ensures that the FastCGI cache is stored in memory, offering faster performance at the expense of RAM utilization.

Validate Nginx FastCGI Cache Functionality on Ubuntu

Test FastCGI Cache with curl

You can validate that FastCGI Cache is working correctly by using the curl command. Depending on your cache settings, you might need to run the command several times before you see a cache hit:

curl -I http://www.your-domain.com

If you don’t have curl installed, you can install it with:

sudo apt install curl -y

In the output, look for the X-FastCGI-Cache: HIT header:

~$ curl -I https://www.example.com/
HTTP/1.1 200 OK
...
X-FastCGI-Cache: HIT
...

This indicates that the request was served from the cache.

Configure Cache Exclusions

Website elements like WordPress admin pages, comment sections, and sitemaps should not be cached. To configure Nginx not to cache these, add the following code above the location (~\.php$) line in your server block file:

# Cache by default
set $skip_cache 0;

# Don't cache URIs containing the following
if ($request_uri ~* "/wp-admin/|/xmlrpc.php|wp-..php|^/feed/|/tag/./feed/|index.php|/.sitemap..(xml|xsl)") {
    set $skip_cache 1;
}

# Don't cache for logged-in users or comment authors
if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_no_cache|wordpress_logged_in") {
    set $skip_cache 1;
}

# POST requests and URIs with a query string should bypass the cache
if ($request_method = POST) {
    set $skip_cache 1;
}

if ($query_string != "") {
    set $skip_cache 1;
}

Debugging Cache Exclusions (Optional)

If you want to add notes for debugging purposes, you can include a custom note under each set $skip_cache 1; statement like this:

set $skip_reason "your custom note";

This can be useful for understanding why certain content is not being cached during troubleshooting.

After making these configurations, make sure to test the configuration and restart Nginx:

sudo nginx -t
sudo systemctl restart nginx

Best Practices and Considerations with Nginx FastCGI Cache on Ubuntu

While FastCGI caching can offer significant performance benefits, it’s essential to ensure that the configuration is optimized for your specific use case and server resources:

  • Evaluate the amount of RAM available before opting for tmpfs for caching. Ensure that your server has enough memory for other critical processes.
  • Tailor the cache exclusions to suit your application. The examples provided are specifically for WordPress, but you might need different exclusions for other types of applications.
  • Regularly monitor the cache usage and performance. If the cache consumes too much disk space or does not improve performance as expected, consider adjusting the cache path, size, or settings accordingly.

Conclusion

Well, there you have it! We’ve walked through the steps to install Nginx FastCGI Cache on your Ubuntu server, offering a boost in your website’s performance by efficiently handling dynamic content. Remember, maintaining your cache settings to suit your site’s needs is key to maximizing the benefits. Don’t shy away from tweaking settings to find that sweet spot. Whether you’re a seasoned pro or new to server management, we hope this guide has been a handy companion in optimizing your web presence. Keep it simple, stay consistent, and here’s to a speedier, smoother website experience for you and your visitors!

Leave a Comment