Enable Browser Cache in Nginx: Step-by-Step Guide
In this article
Enabling browser cache in Nginx improves website performance by instructing visitors' browsers to store static files locally, reducing server load and speeding up page loads on repeat visits. This is achieved by setting appropriate HTTP cache headers for resources like images, CSS, and JavaScript. Before configuring caching, ensure you have access to your Nginx configuration files and a basic understanding of server administration.
What You'll Need
- Access to your server via SSH or console
- Root or sudo privileges
- Access to Nginx configuration files (usually in
/etc/nginx/) - A text editor such as nano, vim, or emacs
- Basic knowledge of Nginx server blocks (sites-available/sites-enabled)
- A working Nginx web server
Step-by-Step
- Log in to your server using SSH or your preferred access method. Ensure you have administrative privileges to modify system files.
- Navigate to the Nginx configuration directory using the command:
cd /etc/nginx. This is the default location on most Linux distributions. - Open your site's configuration file in a text editor. For example:
sudo nano sites-available/example.com. Replaceexample.comwith your actual site configuration filename. - Locate the server block where your site is defined. It starts with
server {and contains directives likelisten,server_name, androot. - Add location blocks for static file types inside the server block to apply cache headers. Use this sample configuration:
location ~* \.(jpg|jpeg|png|gif|ico|css|js|pdf|txt|svg|woff|woff2|ttf|eot)$ { expires 30d; add_header Cache-Control "public, no-transform"; }This matches common static file extensions and sets them to expire in 30 days. Adjust the file types based on your site's content.
- For more granular control, separate cache durations by file type. Example:
location ~* \.css$ { expires 1y; add_header Cache-Control "public"; } location ~* \.js$ { expires 1y; add_header Cache-Control "public"; } location ~* \.(jpg|jpeg|png|gif|ico|svg)$ { expires 1M; add_header Cache-Control "public"; }This sets long-term caching for CSS and JS (1 year), and 1 month for images.
- For HTML and dynamic content, disable caching to ensure freshness. Add:
location ~* \.(html|htm)$ { expires -1; add_header Cache-Control "no-store, no-cache, must-revalidate"; }This prevents browsers from storing HTML files.
- Save the configuration file and exit the editor. In nano, press
CTRL+O, thenENTERto save, andCTRL+Xto exit. - Test the Nginx configuration for syntax errors:
sudo nginx -t. If errors appear, review your changes and correct any typos or misplaced brackets. - Reload Nginx to apply changes:
sudo systemctl reload nginx. This applies the new cache settings without interrupting active connections. - Verify caching is working by visiting your site and inspecting network headers using browser developer tools. Check that static files return
Cache-ControlandExpiresheaders with correct values.
Common Mistakes
- Forgetting to reload Nginx: After editing config files, a reload is required. A restart (
restart) works but causes brief downtime; usereloadinstead. - Incorrect file path matching: Regex patterns are case-sensitive by default. Use
~*for case-insensitive matching (e.g.,.JPGvs.jpg). - Caching dynamic content: Accidentally caching PHP-generated pages or HTML can serve stale content. Exclude dynamic file types explicitly.
- Over-caching with no cache busting: Long expiration times require versioned filenames (e.g.,
style.v2.css) to force updates when files change. - Missing semicolons: Each directive must end with a semicolon. Missing ones cause
nginx -tto fail.
Tips
- Use versioned filenames or query strings (e.g.,
script.js?v=2) to bypass browser cache when updating static files. - Set longer cache times for assets unlikely to change, like fonts or logo images.
- Combine cache headers with Gzip or Brotli compression for faster delivery.
- Use
add_headercarefully in location blocks—headers are not inherited by nested locations. - Monitor cache effectiveness using browser dev tools or tools like PageSpeed Insights.
Troubleshooting
If caching does not work as expected:
- Check configuration syntax: Always run
nginx -tbefore reloading. Fix any reported errors. - Verify location block priority: Nginx uses the most specific location match. Ensure no conflicting blocks override your cache rules.
- Inspect response headers: Use browser dev tools (Network tab) to confirm
Cache-ControlandExpiresheaders are present and correct. - Clear browser cache before testing. Old responses may still be served from disk.
- Check for proxy or CDN interference: If using Cloudflare or similar, they may override or modify cache headers. Adjust CDN settings accordingly.
- Ensure file types are served correctly: Misconfigured MIME types can cause Nginx to skip location rules. Verify with
curl -I filename.css.
Frequently Asked Questions
Does enabling browser cache reduce server bandwidth?
Yes. Cached files are loaded from the visitor's device, reducing repeated downloads from your server and lowering bandwidth usage.
How long should I set cache expiration?
Set long expirations (1 year) for unchanged assets like CSS and JS. Use shorter durations (7–30 days) for images or assets that may update occasionally.
Can I cache files conditionally based on URL path?
Yes. Use location blocks targeting specific paths, such as location /static/ or location /assets/, to apply caching only to designated directories.
Why aren’t my CSS files being cached?
This may be due to incorrect file extension matching, conflicting location blocks, or missing expires directives. Verify the configuration and test headers with curl.
Do I need to enable caching for every site individually?
You can define cache rules in individual server blocks or include them globally in nginx.conf using an include directive for reuse across sites.
Does browser cache work on HTTPS sites?
Yes. Browser caching works identically on HTTPS and HTTP sites. The protocol does not affect cache behavior.