How to Clear The Cache of Nginx?

Published June 30, 2024

Problem: Nginx Cache Buildup

Nginx, a common web server and reverse proxy, uses caching to improve performance. Over time, this cache can collect old or unneeded data. This buildup can cause slower response times, more disk usage, and possibly serve old content to users. Clearing the Nginx cache often is important to keep good server performance and provide current information.

Solution: Methods to Clear Nginx Cache

Manually Deleting Cache Files from the Cache Directory

To clear the Nginx cache manually, find the cache directory in your Nginx configuration file. Use terminal commands to delete the cache files. For example, use "rm -rf /path/to/cache/*" to remove all files in the cache folder. Stop Nginx before clearing the cache to avoid issues.

Restarting the Nginx Server

Restarting the Nginx server clears the cache. On Linux, use "sudo systemctl restart nginx". For macOS, use "sudo nginx -s reload". On Windows, restart Nginx through the Services application. This method clears all cached content but may cause website downtime.

Using Nginx Configuration Options

Using proxy_cache_bypass Directive

The proxy_cache_bypass directive lets you bypass the cache for specific requests. Add the directive to your Nginx configuration file. For example, add "proxy_cache_bypass $http_cache_control;" to bypass the cache when a specific header is in the request.

Implementing Cache Purge Module

The Nginx Cache Purge module allows you to clear specific URLs from the cache. Install the module, then configure it in your Nginx configuration file. Add a location block to define how to handle purge requests. This method offers more control but needs extra setup.

Advanced Techniques for Clearing Nginx Cache

Automating Cache Clearing with Shell Scripts

To automate cache clearing, create a shell script. Here's an example:

#!/bin/bash
rm -rf /path/to/nginx/cache/*
nginx -s reload

Save this script with a .sh extension and make it executable using the chmod command.

To schedule cache clearing tasks, use the cron job scheduler. Open the crontab file with:

crontab -e

Add a line to run your script at set times. For example, to clear the cache daily at midnight:

0 0 * * * /path/to/your/script.sh

Implementing Cache Control Headers

Cache-Control headers help manage how content is cached. Add these headers in your Nginx configuration:

location / {
    add_header Cache-Control "public, max-age=3600";
}

This example sets content to be publicly cacheable for one hour.

Other useful Cache-Control directives include:

  • no-cache: Requires validation before using cached content
  • no-store: Prevents caching of sensitive information
  • must-revalidate: Checks if cached content is still valid before use

Adjust these headers based on your caching needs.