Reduce Repeated Transfers with Caching and Compression
🎯 Introduction
Once the site works, repeatedly downloading the same files wastes time. This article reduces transfers in two ways: letting browsers reuse downloaded resources and compressing text that still needs to be sent.
🧱 Plan How Cached Content Will Be Updated
Browser caching stores responses on the visitor's computer. The Cache-Control response header determines when they can be reused directly and when the browser must check with the server.
| Setting | Main meaning | Use in this course |
|---|---|---|
no-cache | May be stored, but must be validated before reuse | HTML entry point |
no-store | The response should not be stored | Certain sensitive responses, as determined by the application |
public, max-age=3600 | Shared caches may store it, and it can be reused directly for one hour | Files confirmed to be public and suitable for short-term reuse |
no-cache does not prohibit storage. If validation confirms that the content has not changed, the server may return only 304 Not Modified, without the full file body.
Build tools often generate filenames such as app.a1b2c3.js that change when the content changes. Long cache lifetimes are suitable only when this update strategy is guaranteed. The course uses a fixed site.css filename, so start with a short lifetime to observe the behavior.
🛠 Use Different Rules for Assets and the Entry Point
Open $HOME/nginx-course/conf/servers/site.conf. Replace the existing location ^~ /assets/ block inside server { ... }, keeping the index rule from the previous article.
location ^~ /assets/ {
try_files $uri =404;
add_header Cache-Control 'public, max-age=60';
}
try_files $uri =404; checks whether the requested file exists. For example, when the browser requests /assets/site.css?v=2, $uri is /assets/site.css; the query string ?v=2 is not part of the lookup. With root html;, Nginx looks for $HOME/nginx-course/html/assets/site.css. It sends the CSS if found; otherwise, =404 returns HTTP 404. Mistyped static resource paths therefore produce an explicit 404. Nginx try_files documentation
add_header adds a response header. This example omits always so it does not force this cache policy onto 404 responses. Do not also use expires to generate another set of cache directives. Start with one explicit source. See the official headers module documentation for applicable status codes and inheritance.
Check and reload, then use curl -I to view only response headers:
curl -I http://127.0.0.1:8080/index.html
curl -I http://127.0.0.1:8080/assets/site.css
Expect no-cache and public, max-age=60, respectively. curl does not cache responses by default, so these commands inspect policy rather than demonstrate browser reuse. Use the browser's developer tools to inspect caching on repeat visits.
🧰 Enable Text Compression
Nginx sends a response body over the network when the browser first downloads CSS, or when an expired cached version needs downloading again. With gzip enabled, Nginx compresses eligible responses when the browser advertises gzip support. The browser decompresses the response automatically and uses the CSS normally, while fewer bytes need to be downloaded.
Open $HOME/nginx-course/conf/nginx.conf and add the following five gzip directives inside the existing http { ... } block, for example above include servers/*.conf;. Four-space indentation aligns directives at the same level; Nginx uses braces to determine context. The downloadable course package already includes these five lines in its main configuration.
http {
# Keep the existing configuration here
gzip on;
gzip_min_length 1024;
gzip_comp_level 5;
gzip_vary on;
gzip_types text/css application/javascript application/json text/plain;
include servers/*.conf;
}
gzip_types adds CSS, JavaScript, JSON, and the exercise's text/plain content to the HTML compression supported by default. gzip_min_length 1024 uses the response's Content-Length header; responses with a known length below 1024 bytes are not compressed. gzip_comp_level 5 sets the compression level; higher levels generally use more CPU. gzip_vary on adds Vary: Accept-Encoding so caches distinguish requests advertising gzip support from those that do not. Nginx gzip documentation
The course's example site.css is only 126 bytes, below the compression threshold, so use the larger large.txt to observe compression. The download includes this file. If you created the exercise directory manually, run the following Bash command to generate 7500 bytes of test text.
printf 'nginx learning %.0s' {1..500} > "$HOME/nginx-course/html/assets/large.txt"
After checking and reloading, send two GET requests for the same file. The second includes Accept-Encoding: gzip, telling Nginx that the client can accept gzip.
ngx -t && ngx -s reload
curl -sS -o /dev/null -w '%{size_download} bytes\n' \
http://127.0.0.1:8080/assets/large.txt
curl -sS -D - -o /dev/null -w '%{size_download} bytes\n' \
-H 'Accept-Encoding: gzip' http://127.0.0.1:8080/assets/large.txt
Both commands download the body and discard its contents. %{size_download} reports the number of response body bytes actually received. The second also prints headers: expect Content-Encoding: gzip and a substantially smaller download.
❓ Questions and Answers
Q1: Is a longer cache lifetime always better?
It must match the update strategy. Caching a fixed filename for too long can leave users seeing old content for a long time.
Q2: Is this Nginx proxy caching?
No. These settings control how browsers and intermediate caches store responses. They do not enable proxy_cache for backend API responses.
🧪 Exercise
Change the asset max-age to 120, reload, and inspect the response headers. Then change the URL in the request with Accept-Encoding: gzip above to http://127.0.0.1:8080/assets/site.css and inspect the small file's response.
Expect Cache-Control: public, max-age=120. The example CSS file is smaller than 1024 bytes, so its response has no Content-Encoding: gzip header.
🎉 You can now control both how often content is downloaded and how many bytes each transfer requires!
