User Agents

Web browsers and everyday web tech, explained

How to Cache Static Content in Nginx

· 4 min read · Cookies and Cache

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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

  1. 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/default or a custom domain file.
  2. 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.
  3. Add location blocks for static files
    Inside the server block of your configuration, add a location directive for each file type or group them using a regex. For example:
    location ~* \.(css|js|png|jpg|jpeg|gif|ico|svg|woff|woff2)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
    This matches file extensions and applies long-term caching.
  4. Set expiration times
    Use the expires directive to define how long browsers should cache files. Common values:
    • 1y – one year (ideal for versioned assets)
    • 1M – one month
    • 7d – seven days
    • off – disables caching
    Use longer durations for files that won’t change often.
  5. Add Cache-Control headers
    Include the add_header Cache-Control directive to specify caching behavior. For static assets, use:
    add_header Cache-Control "public, immutable";
    public allows caching by browsers and intermediaries. immutable tells browsers not to revalidate, assuming the file won’t change during the expiry period.
  6. 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:
    expires 1w;
    This balances performance and freshness.
  7. Exclude dynamic or sensitive content
    Ensure caching rules don’t apply to dynamic files like .php or .html. Use negative lookahead or separate location blocks:
    location ~* \.(css|js|png|jpg|jpeg|gif)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
    Avoid applying caching to paths like /admin or /api.
  8. Test your configuration
    Run sudo nginx -t to check for syntax errors. Fix any issues reported before proceeding.
  9. Reload Nginx
    Apply changes with sudo systemctl reload nginx. This reloads the configuration without dropping connections.
  10. Verify caching headers
    Use browser Developer Tools (Network tab) or curl -I yourdomain.com/style.css to check the response headers. Confirm that Cache-Control and Expires are 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 expires in the main server block without conditions, as it may affect dynamic content.

Tips

  • Use immutable only 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_path if 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.log to 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.