You can achieve time-based caching in Nginx using purely declarative configuration by leveraging the map directive to define different cache durations based on the time of day. Nginx doesn't have built-in time-based logic, but you can use the $time_local variable (or similar) to extract the hour of the day and map it to different cache durations.
Here’s how you can set up an Nginx configuration to cache content for a longer time during the night (e.g., 12 AM to 6 AM) and a shorter time during the day (e.g., 6 AM to 12 AM), without using Lua or other scripting.
Step-by-Step Configuration
-
Enable Proxy Caching
First, set up a proxy cache to store the content. This is done using the proxy_cache directive.
-
Use map to Define Cache Duration Based on Time
Use the map directive to dynamically set the cache duration based on the hour of the day. The $time_local variable provides the local time in a format like Wed, 04 Oct 2023 14:30:00 +0000, and you can extract the hour using string manipulation.
-
Apply the Cache Duration
Use the mapped value to set the proxy_cache_valid directive dynamically.
Here’s an example configuration:
http {
# Define the cache path and settings
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=1g inactive=60m use_temp_path=off;
# Map the hour of the day to a cache duration
map $time_local $cache_duration {
# Extract the hour from $time_local (format: "Wed, 04 Oct 2023 HH:MM:SS +0000")
# We use a regex to match the hour (HH) and map it to a cache duration
~^\w+,\s+\d+\s+\w+\s+\d+\s+(?<hour>\d{2}): $hour;
# Night time (12 AM to 6 AM): Cache for 6 hours (360 minutes)
"00" 360m;
"01" 360m;
"02" 360m;
"03" 360m;
"04" 360m;
"05" 360m;
# Day time (6 AM to 12 AM): Cache for 10 minutes
default 10m;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend_server; # Replace with your backend
proxy_cache my_cache; # Enable caching using the defined cache zone
proxy_cache_valid 200 301 302 $cache_duration; # Use the mapped cache duration
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
proxy_cache_background_update on; # Optional: Update cache in the background
proxy_cache_lock on; # Optional: Prevent cache stampede
# Add cache status to response headers (for debugging)
add_header X-Cache-Status $upstream_cache_status;
}
}
}
Explanation of the Configuration
-
proxy_cache_path
This defines the cache storage location (/var/cache/nginx), the cache zone name (my_cache), and other settings like the maximum size (max_size=1g) and how long inactive items stay in the cache (inactive=60m).
-
map Directive
- The
$time_local variable contains the current local time in a format like Wed, 04 Oct 2023 14:30:00 +0000.
- The regex
~^\w+,\s+\d+\s+\w+\s+\d+\s+(?<hour>\d{2}): extracts the hour (HH) into a named capture group called hour.
- The
map block then maps specific hours to cache durations:
- From 00:00 to 05:59 (night), the cache duration is set to
360m (6 hours).
- For all other hours (day), the cache duration defaults to
10m (10 minutes).
-
proxy_cache_valid
- This directive sets the cache duration for successful responses (HTTP 200, 301, 302).
- By using
$cache_duration, the cache duration is dynamically set based on the time of day.
-
Optional Cache Features
proxy_cache_use_stale: Allows serving stale content in case of errors or while the cache is being updated.
proxy_cache_background_update: Updates the cache in the background to avoid serving stale content to users.
proxy_cache_lock: Prevents multiple requests from triggering simultaneous cache updates (cache stampede protection).
add_header X-Cache-Status: Adds a header to responses to indicate whether the response was served from the cache (HIT, MISS, etc.).
Notes and Considerations
-
Time Zone
The $time_local variable uses the server's local time. Ensure your server's time zone is correctly configured to match your desired "day" and "night" periods. If you need to use a different time zone, you may need to adjust the logic or use a different approach (though this would likely require scripting, which you want to avoid).
-
Cache Invalidation
This setup does not handle cache invalidation. If content changes during the night, it will remain cached for up to 6 hours unless you implement a cache purge mechanism (e.g., using proxy_cache_purge with a custom trigger).
-
Testing
Test the configuration thoroughly, especially the regex in the map block, to ensure it correctly extracts the hour and applies the desired cache duration. You can use the X-Cache-Status header to debug cache behavior.
-
Limitations of Declarative Approach
The declarative approach using map and $time_local is somewhat limited. For more complex time-based logic (e.g., handling minutes or specific days), you might need to resort to scripting (e.g., Lua or JavaScript via njs). However, the above configuration meets your requirement of being purely declarative.
-
Performance
This configuration is efficient and does not introduce significant overhead, as the map directive is evaluated only once per request.
Example Usage
- At 3:00 AM, a request to
/page will be cached for 6 hours (until 9:00 AM).
- At 10:00 AM, a request to
/page will be cached for 10 minutes (until 10:10 AM).
This setup ensures that content is cached longer during the night when changes are less frequent, while keeping the cache duration short during the day when updates are more likely.