Sometimes you find yourself in a situation where you need to clear the Nginx proxy cache for a specific set of URLs, particularly those following a wildcard pattern like
www.website.com/folder/*. Surprisingly, Nginx, in its standard offering, doesn't provide a straightforward way to do this. They probably want you to upgrade to Nginx Plus for such "advanced" features. But fear not! There's a DIY workaround that's both effective and satisfyingly rebellious.
First, let's dive into how Nginx generates its cache key. In my case it is:
It's a combination of the request schema, method, host, and path. It can be different in your case, and knowing this is crucial for our task.
To clear the cache for all URLs starting with
www.website.com/folder/, use the following command:
sudo grep -lr "GETwww.website.com/folder/" /path/to/nginx/cache/ | sudo xargs rm
grep -lr "GETwww.website.com/folder/" /path/to/nginx/cache/ searches through the Nginx cache directory for files containing the string
-l flag tells
grep to only output the names of files with matching content, and
-r makes the search recursive.
xargs rm: The output (i.e., the list of cache files matching our criteria) is then piped to
xargs rm, which, as you might guess, removes these files.
Cache Cleared: Voilà! The cache for all URLs under
www.website.com/folder/* is now cleared.
So there you have it. You don't need Nginx Plus to manage your cache smartly. A little command-line ingenuity is all it takes. Just be sure to use this power wisely – and maybe don't tell Nginx that their Plus version isn't always necessary for such tasks. 😉
proxy_cache_key in your config files, becasue the keys might be generated differently in your setup. Also be cautious when using commands like
rm and always ensure you're targeting the right files. It's better to be safe than sorry, especially when dealing with server configurations.