0
0
NginxHow-ToBeginner · 3 min read

How to Set Cache Expiration in Nginx for Efficient Caching

To set cache expiration in nginx, use the expires directive inside a location or server block to specify how long browsers should cache content. For example, expires 1d; sets the cache to expire after one day.
📐

Syntax

The expires directive controls the cache expiration time sent in the Cache-Control and Expires headers. It is used inside location, server, or http blocks.

  • expires time; — sets the cache duration (e.g., 1d for one day, 10m for ten minutes).
  • expires off; — disables caching.
  • expires epoch; — sets expiration to a date in the past, effectively disabling caching.
nginx
location /images/ {
    expires 30d;
}
💻

Example

This example sets cache expiration for static files like images and CSS to 30 days, improving load speed by telling browsers to reuse cached files for that time.

nginx
server {
    listen 80;
    server_name example.com;

    location /images/ {
        expires 30d;
        add_header Cache-Control "public";
    }

    location /css/ {
        expires 7d;
        add_header Cache-Control "public";
    }

    location / {
        expires off;
    }
}
⚠️

Common Pitfalls

Common mistakes when setting cache expiration in Nginx include:

  • Not using add_header Cache-Control along with expires, which can cause inconsistent caching behavior.
  • Setting too long expiration for dynamic content, causing users to see outdated data.
  • Placing expires outside of a valid block like location or server, which makes it ineffective.
nginx
location /api/ {
    expires 30d;  # Wrong: API responses usually should not be cached this long
}

# Correct approach:
location /api/ {
    expires off;
    add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0";
}
📊

Quick Reference

DirectiveDescriptionExample
expiresSets cache expiration timeexpires 10m;
expires offDisables cachingexpires off;
expires epochExpires immediately (past date)expires epoch;
add_header Cache-ControlControls cache behavior explicitlyadd_header Cache-Control "public";

Key Takeaways

Use the expires directive inside location or server blocks to set cache expiration.
Combine expires with add_header Cache-Control for consistent caching behavior.
Avoid long cache times for dynamic content to prevent stale data.
Use expires off; to disable caching when needed.
Place cache directives correctly inside valid Nginx blocks for them to work.