Adding a cache layer to NGINX Reverse Proxy

Start off by logging onto your server using SSH.

Create a directory to store the cache files

mkdir -p /var/cache/nginx

Change the ownership of that folder so that the NGINX user can access it

 chown nginx:nginx /var/cache/nginx/

Open the NGINX configuration file

nano /etc/nginx/conf.d/nginx.conf

You need to set two directives, the proxy_cache_path (which lives in a different configuration file as outlined below) which we just created, and the proxy_cache.

/etc/nginx/nginx.conf -> proxy_cache_path

/etc/nginx/conf.d/nginx.conf -> proxy_cache


Just a note that this path does not go into the etc/nginx/conf.d/nginx.conf file like it says in the documentation. Instead, it needs to reside inside the http {} reference which occurs in /etc/nginx/nginx.conf. This file gets parsed, and then pulls in the other file with the rules about the proxy_cache.

proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=nft_cache:10m max_size=10g inactive=1440m use_temp_path=off;


 location / {
                proxy_cache nft_cache;
                proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504 http_429;
                proxy_cache_background_update on;
                proxy_cache_lock on;

Adding headers in the cached response

I wanted to see in teh browser if the responses were coming from the NGINX cache or from Cloudflare.

add_header X-Cache-Status $upstream_cache_status;

Leave a comment

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