How to Cache Static Content in Nginx
In this article
Caching static content in Nginx improves website performance by reducing server load and speeding up content delivery. Static files like images, CSS, JavaScript, and fonts are served faster to returning visitors because they are stored in the browser’s cache. This guide walks you through configuring Nginx to cache static assets effectively, ensuring faster load times and reduced bandwidth usage.
What You'll Need
- Nginx installed and running on your server
- Access to your Nginx configuration files (typically in
/etc/nginx/) - Sudo or root privileges to edit and reload Nginx
- A text editor (e.g., nano, vim)
- Basic understanding of Nginx server blocks (virtual hosts)
Step-by-Step
- Locate your Nginx configuration file
The main configuration is usually at/etc/nginx/nginx.conf, but site-specific settings are often in/etc/nginx/sites-available/. Open the file for your website, such as/etc/nginx/sites-available/defaultor a custom domain file. - Identify static file types
Determine which file extensions represent static content. Common ones include:
.css, .js, .png, .jpg, .jpeg, .gif, .ico, .svg, .pdf, .woff, .woff2
You’ll use these in location blocks to apply caching rules. - Add location blocks for static files
Inside theserverblock of your configuration, add alocationdirective for each file type or group them using a regex. For example:
This matches file extensions and applies long-term caching.location ~* \.(css|js|png|jpg|jpeg|gif|ico|svg|woff|woff2)$ { expires 1y; add_header Cache-Control "public, immutable"; } - Set expiration times
Use theexpiresdirective to define how long browsers should cache files. Common values:1y– one year (ideal for versioned assets)1M– one month7d– seven daysoff– disables caching
- Add Cache-Control headers
Include theadd_header Cache-Controldirective to specify caching behavior. For static assets, use:add_header Cache-Control "public, immutable";publicallows caching by browsers and intermediaries.immutabletells browsers not to revalidate, assuming the file won’t change during the expiry period. - Handle versioned vs. unversioned assets
If your files include hashes in filenames (e.g.,app.a1b2c3.js), use long expiry times. If not, reduce expiry to avoid stale content. For unversioned files, consider:
This balances performance and freshness.expires 1w; - Exclude dynamic or sensitive content
Ensure caching rules don’t apply to dynamic files like.phpor.html. Use negative lookahead or separate location blocks:
Avoid applying caching to paths likelocation ~* \.(css|js|png|jpg|jpeg|gif)$ { expires 1y; add_header Cache-Control "public, immutable"; }/adminor/api. - Test your configuration
Runsudo nginx -tto check for syntax errors. Fix any issues reported before proceeding. - Reload Nginx
Apply changes withsudo systemctl reload nginx. This reloads the configuration without dropping connections. - Verify caching headers
Use browser Developer Tools (Network tab) orcurl -I yourdomain.com/style.cssto check the response headers. Confirm thatCache-ControlandExpiresare present and correct.
Common Mistakes
- Caching HTML files: HTML is often dynamic. Caching it can serve stale pages. Only cache HTML if it’s truly static.
- Using long expiry without versioning: If a CSS file changes but keeps the same name, users may not see updates. Always version static files or use shorter expiry.
- Overlapping location blocks: Nginx processes location blocks in order. A broad rule might override a specific one. Use regex carefully and test.
- Forgetting to reload Nginx: Editing the config does nothing until you reload. Always run
systemctl reload nginx. - Applying caching globally: Avoid placing
expiresin the main server block without conditions, as it may affect dynamic content.
Tips
- Use
immutableonly for versioned assets. It prevents revalidation, so changes won’t be detected. - Set different expiry times for different file types. Fonts and images can be cached longer than scripts.
- Combine caching with Gzip compression for even better performance.
- Use
proxy_cache_pathif you’re also caching dynamic content via reverse proxy, but that’s beyond basic static caching. - Monitor log files with
tail -f /var/log/nginx/access.logto see how static files are being served.
Troubleshooting
If caching isn’t working, start by checking the browser’s Network tab. If Cache-Control or Expires headers are missing, the location block may not be matching. Verify the regex pattern and ensure it’s inside the correct server block. Run nginx -t again to rule out syntax errors. If headers appear but files aren’t cached, ensure the file actually exists and is served by Nginx, not a backend application. Clear your browser cache and test with a private window. If using a CDN, ensure it respects origin caching headers. Finally, check file permissions — Nginx must be able to read the static files.
Frequently Asked Questions
Does Nginx cache files on the server?
No, this guide configures browser caching via headers. Nginx does not store static files in memory unless using open_file_cache or reverse proxy caching.
How do I clear cached files in the browser?
Users can hard refresh (Ctrl+Shift+R) or clear their browser cache. As a developer, append a version query (e.g., style.css?v=2) to force reload.
Can I cache static content on HTTPS sites?
Yes, caching works the same over HTTPS. The headers are sent regardless of encryption.
Why is my CSS not updating?
Long expiry with no versioning causes this. Rename the file or shorten the expires time during development.
Should I cache favicon.ico?
Yes, it’s a static file. Use a long expiry since it rarely changes.
Does caching improve SEO?
Yes, faster load times from caching are a ranking factor. Google favors performant websites.