This is a technique that allows you to efficiently cache content on the user's machine, thereby increasing the performance of the application.
Please refer to the following example
worker_processes auto;
events {
worker_connections 1024;
}
http {
include /env/nginx/mime.types;
server {
listen 80;
server_name nglearns.test;
root /srv/nglearns/static-demo;
location ~* \.(css|js|jpg)$ {
access_log off;
add_header Cache-Control public;
add_header Pragma public;
add_header Vary Accept-Encoding;
expires 1M;
}
}
}
in the example above, by using the location ~* .(css|js|jpg)$ you can tell nginx that we are referring to files with the extensions css, js, and jpg.
Next, we will use the add_header directive to always add the header for the appropriate extensions, in this case Cache-Control public to tell the client that this content will be cached in all cases.
In addition, we can use Pragma, it is an old version like Cache-Control and also performs similar features to Cache-Control
As for the Vary header, it will inform the client that the cached content may vary, and setting the Accept-Encoding means that the content depends on the encoding will be accepted from the client.
And finally, the expires directive, this attribute allows the client to understand how long this information will be cached:
To experiment, we will run the following command
curl -I http://nglearns.test/demo.jpg
Result
# HTTP/1.1 200 OK
# Server: nginx/1.18.0 (Ubuntu)
# Date: Sun, 25 Apr 2021 15:58:22 GMT
# Content-Type: image/jpeg
# Content-Length: 19209
# Last-Modified: Sun, 25 Apr 2021 08:35:33 GMT
# Connection: keep-alive
# ETag: "608529d5-4b09"
# Expires: Tue, 25 May 2021 15:58:22 GMT
# Cache-Control: max-age=2592000
# Cache-Control: public
# Pragma: public
# Vary: Accept-Encoding
# Accept-Ranges: bytes
Here we can see that the header has been added with the attributes we have set.