0
0
NginxHow-ToBeginner · 3 min read

How to Set Expires Header in Nginx for Cache Control

To set the expires header in Nginx, use the expires directive inside a location or server block. This directive controls how long browsers cache static files by specifying a time duration or a date.
📐

Syntax

The expires directive sets the caching time for responses. It accepts values like off, epoch, max, or a time duration such as 30d (30 days), 1h (1 hour), etc.

Example parts:

  • expires 30d; — cache for 30 days
  • expires off; — disable caching
  • expires max; — cache for maximum time (about 10 years)
nginx
location /images/ {
    expires 30d;
}
💻

Example

This example sets the expires header to 7 days for all files in the /static/ folder. Browsers will cache these files for one week, reducing server load and speeding up page loads.

nginx
server {
    listen 80;
    server_name example.com;

    location /static/ {
        root /var/www/html;
        expires 7d;
    }
}
Output
When a browser requests a file under /static/, the response header will include: Expires: <date 7 days in the future>
⚠️

Common Pitfalls

Common mistakes when setting the expires header include:

  • Placing the expires directive outside a location or server block, which causes errors.
  • Using incorrect time formats like 30days instead of 30d.
  • Not reloading Nginx after changes, so the new settings don't apply.
  • Setting very long cache times for files that change often, causing stale content.
nginx
location /assets/ {
    expires 30days;  # Incorrect, should be 30d
}

# Correct:
location /assets/ {
    expires 30d;
}
📊

Quick Reference

DirectiveMeaningExample
expires off;Disable cachingexpires off;
expires epoch;Set expiry to 1 Jan 1970 (immediate expiry)expires epoch;
expires max;Set expiry to maximum (about 10 years)expires max;
expires 1h;Cache for 1 hourexpires 1h;
expires 30d;Cache for 30 daysexpires 30d;

Key Takeaways

Use the expires directive inside location or server blocks to control caching.
Specify cache duration with time units like d for days or h for hours (e.g., expires 7d;).
Avoid very long cache times for frequently updated files to prevent stale content.
Always reload Nginx after changing configuration to apply new settings.
Use expires off; to disable caching when needed.