Zac Fukuda
057

Nginx Cache on Ubuntu

Environment

  • OS: Ubuntu 22.04.3
  • Nginx: 1.18.0

Configuration

I think it is better to keep nginx.conf as much original as possible, and to make a dedicated configuration file for cache.

sudo vi /etc/nginx/conf.d/cache.conf

And the content of cache.conf shall be:

proxy_cache_path /var/lib/nginx/cache levels=1:2 keys_zone=mycache:10m inactive=60m use_temp_path=off;

Usually we save a site configuration under /etc/nginx/sites-available and make a symbolic file under /etc/nginx/sites-enabled. Open your site configuration with:

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

The content of that configuration file shall be:

server {
	location / {
		…
		proxy_cache mycache;
	}

	# Any extension you want to cache
	location ~* \.(css|jpg|jpeg|js|json|otf|png|svg|webp)$ {
		add_header Cache-Control "public, max-age=2592000";
	}
}

The value of proxy_cache must match the keys_zone value defined in nginx.conf.

In the configuration just above, the max-age is 2592000 seconds, that is 30 days. You can also add Cache-Control header in other way:

location ~* \.(css|jpg|jpeg|js|json|otf|png|svg|webp)$ {
		expires 30d; # e.x. 1d, 1M, 1y
		add_header Cache-Control "public, no-transform";
	}

Cache Directory

Create a directory for cache you defined in nginx.conf for proxy_cache_path and modify ownership:

sudo mkdir /var/lib/nginx/cache 
sudo chown -R www-data:root /var/lib/nginx/cache
sudo chmod -R 700 /var/lib/nginx/cache

The owner user of /var/lib/nginx/cache must match user value in nginx.conf.

When we check the ownership of /var/lib/nginx, it shall be something as follows:

drwx------  2 www-data root 4096 Feb  5 19:03 body
drwx------  2 www-data root 4096 Feb  6 16:25 cache
drwx------  2 www-data root 4096 Jul 27  2021 fastcgi
drwx------ 12 www-data root 4096 Mar  8  2022 proxy
drwx------  2 www-data root 4096 Jul 27  2021 scgi
drwx------  2 www-data root 4096 Jul 27  2021 uwsgi

Test Config

Run Nginx test command:

sudo nginx -t

If the configuration is OK, the output will be:

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

Restart Nginx

Restart Nginx so that the modification is effective:

sudo service nginx restart

Ensure if you can access to your web application.

Resources