0
0
NginxHow-ToBeginner · 3 min read

How to Cache Static Files in Nginx for Faster Loading

To cache static files in nginx, use the location block to match static file types and set expires and add_header Cache-Control directives. This tells browsers to store files locally for a set time, speeding up page loads.
📐

Syntax

The basic syntax to cache static files in nginx involves using a location block to target file types and setting caching headers.

  • location: Defines the URL pattern to match static files.
  • expires: Sets how long browsers should keep the cached files.
  • add_header Cache-Control: Adds HTTP headers to control caching behavior.
nginx
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
    expires 30d;
    add_header Cache-Control "public, no-transform";
}
💻

Example

This example configures nginx to cache common static files like images, CSS, and JavaScript for 30 days. It improves load speed by telling browsers to reuse files without asking the server again during that time.

nginx
server {
    listen 80;
    server_name example.com;

    root /var/www/html;

    location / {
        index index.html;
    }

    location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
        expires 30d;
        add_header Cache-Control "public, no-transform";
    }
}
⚠️

Common Pitfalls

Common mistakes when caching static files in nginx include:

  • Not matching the correct file extensions in the location block, so files are not cached.
  • Setting expires too short or too long, causing unnecessary reloads or stale content.
  • Forgetting to add Cache-Control headers, which help browsers understand caching rules.
  • Placing caching rules in the wrong location block, causing conflicts.

Example of a wrong and right way:

nginx
# Wrong: Missing file extensions and no caching headers
location /static/ {
    root /var/www/html;
}

# Right: Correct file extensions and caching headers
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
    root /var/www/html;
    expires 30d;
    add_header Cache-Control "public, no-transform";
}
📊

Quick Reference

DirectivePurposeExample Value
locationMatches URL patterns for static files~* \.(jpg|jpeg|png|gif|ico|css|js)$
expiresSets browser cache duration30d
add_header Cache-ControlControls caching behavior in browsers"public, no-transform"

Key Takeaways

Use the location block with file extensions to target static files for caching.
Set expires to a suitable duration like 30 days to improve load speed.
Add Cache-Control headers to clearly instruct browsers on caching rules.
Avoid missing file types or placing caching directives in wrong locations.
Test your configuration to ensure static files are properly cached.