How to Enable Open File Cache in Nginx

Nginx’s open file cache reduces filesystem overhead by caching file descriptors, file metadata, and directory lookups in memory. When your server handles many static file requests, each request normally triggers multiple system calls to open files, check permissions, and read modification times. With open file cache enabled, Nginx stores this information after the first access, allowing subsequent requests to skip the filesystem entirely. This optimization benefits high-traffic static file servers, CDN edge nodes, sites serving many images or assets, and servers running on networked storage where filesystem operations add latency.

This guide walks you through configuring open file cache in Nginx, explains each directive’s purpose, and provides production-ready settings. After completing these steps, you will have a properly tuned cache that reduces server load and improves response times for static content.

Understanding Open File Cache Directives

Before configuring the cache, it’s helpful to understand what each directive controls. Nginx provides four directives that work together to manage the open file cache. You can place these directives at the http, server, or location level depending on how granularly you want to control caching behavior. Placing them in the http block applies the settings globally, while server or location blocks allow different caching strategies for different sites or paths.

open_file_cache

  • Controls whether caching is enabled and sets capacity limits
  • The max parameter sets the maximum number of cached entries
  • The inactive parameter removes entries from cache if they haven’t been accessed within the specified time
  • Set to off to disable caching entirely

open_file_cache_valid

  • Sets how often Nginx revalidates cached entries against the filesystem
  • After this interval, Nginx checks if the file has changed (modification time, size)
  • Lower values catch file changes faster but increase filesystem I/O
  • Default is 60 seconds

open_file_cache_min_uses

  • Sets the minimum access count before a file remains cached
  • Files accessed fewer times than this threshold during the inactive period are evicted
  • Helps prevent rarely accessed files from consuming cache slots
  • Default is 1 (cache after first access)

open_file_cache_errors

  • Controls whether Nginx caches file lookup errors (such as “file not found” or “permission denied”)
  • When enabled, repeated requests for non-existent files skip the filesystem lookup
  • Useful for reducing I/O when clients frequently request missing resources
  • Default is off

For complete documentation on these directives, see the official Nginx open_file_cache reference.

Configure Open File Cache in Nginx

Back Up Your Current Configuration

Before making any changes, create a backup of your Nginx configuration. This allows you to restore the original settings if something goes wrong:

sudo cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak

Edit the Nginx Configuration File

Open the main Nginx configuration file in a text editor:

sudo nano /etc/nginx/nginx.conf

Add the following directives inside the http block to enable open file cache globally. Place them near the top of the block, before any server blocks:

open_file_cache max=10000 inactive=30s;
open_file_cache_valid 60s;
open_file_cache_min_uses 2;
open_file_cache_errors on;

These settings work well for most production servers. The cache holds up to 10,000 file entries, removes unused entries after 30 seconds of inactivity, revalidates cached data every 60 seconds, and caches error responses for missing files.

Example Configuration in Context

The following example shows where to place these directives within a typical nginx.conf file. This is a partial snippet showing only the relevant section; your actual configuration will contain additional directives:

http {
    # MIME types and basic settings
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    # Open file cache settings
    open_file_cache max=10000 inactive=30s;
    open_file_cache_valid 60s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;

    # Other optimizations
    sendfile on;
    tcp_nopush on;

    # Include server blocks
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

Do not copy this entire block over your existing configuration. Instead, locate your existing http block and add only the four open_file_cache* directives. The other lines shown here are for context only.

Save the file by pressing Ctrl+O, then Enter, then exit with Ctrl+X.

Tuning for Different Scenarios

The example values above suit most production environments, but you may want to adjust them based on your specific use case:

High-traffic static file servers

open_file_cache max=50000 inactive=60s;
open_file_cache_valid 120s;
open_file_cache_min_uses 3;
open_file_cache_errors on;

This configuration increases cache capacity and extends validity periods, suitable when you serve many files that rarely change (such as image assets or archived content).

Development or staging environments

open_file_cache max=1000 inactive=10s;
open_file_cache_valid 10s;
open_file_cache_min_uses 1;
open_file_cache_errors off;

This configuration uses shorter intervals so file changes appear quickly. For active development where files change constantly, you may prefer to disable the cache entirely with open_file_cache off; to avoid any stale content issues.

Test and Apply the Configuration

Verify Configuration Syntax

Before applying changes, test the configuration for syntax errors:

sudo nginx -t

A successful test produces output similar to:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

If you see error messages instead, review the line numbers mentioned in the output and verify your syntax matches the examples above. Common mistakes include missing semicolons at the end of directives or placing directives outside the http block.

Reload Nginx to Apply Changes

Once the syntax test passes, reload Nginx to apply the new configuration. Using reload instead of restart allows Nginx to gracefully apply changes without dropping active connections:

sudo systemctl reload nginx

Alternatively, you can use the Nginx signal command:

sudo nginx -s reload

If you need a full restart (for example, after upgrading Nginx binaries), use:

sudo systemctl restart nginx

Verify Open File Cache Is Working

Open file cache operates silently, with no built-in command to view cache contents or hit rates. You can still verify the configuration is active and observe its effects through several methods.

Confirm the Configuration Is Loaded

Check that your directives appear in the running configuration:

sudo nginx -T 2>/dev/null | grep open_file_cache

This command displays the full Nginx configuration being used and filters for your cache settings:

    open_file_cache max=10000 inactive=30s;
    open_file_cache_valid 60s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;

Monitor System Call Reduction

For a more detailed view of the cache’s impact, you can use strace to observe system calls during file serving. Before enabling the cache, Nginx makes multiple open(), stat(), and fstat() calls for each request. After enabling the cache, repeated requests for the same file should show fewer filesystem-related system calls.

Using strace on a production server adds overhead and should only be done briefly for diagnostic purposes. For ongoing monitoring, observe response times and server load rather than tracing system calls.

Troubleshooting Common Issues

Configuration Syntax Errors

If nginx -t reports an error like the following:

nginx: [emerg] unknown directive "open_file_cache" in /etc/nginx/nginx.conf:15

Verify that the directives are placed inside the http block, not at the top level of the file. These directives are only valid within http, server, or location contexts.

Stale Content After File Updates

If you update a file but clients continue receiving the old version, the cached metadata may not have been revalidated yet. This can happen if your open_file_cache_valid interval is set too high. Either wait for the validation interval to pass, reduce the open_file_cache_valid value, or reload Nginx to clear the cache:

sudo systemctl reload nginx

Reloading Nginx clears the open file cache and rebuilds it as new requests arrive.

High Memory Usage

Each cached file entry consumes a small amount of memory for storing the file descriptor and metadata. If you set max to a very high value (such as 100,000 or more) on a server with limited RAM, memory pressure could occur. Monitor your server’s memory usage after enabling the cache and reduce the max value if necessary.

Restoring the Original Configuration

If you need to revert your changes, restore the backup you created earlier:

sudo cp /etc/nginx/nginx.conf.bak /etc/nginx/nginx.conf
sudo nginx -t && sudo systemctl reload nginx

When to Use Open File Cache

Open file cache provides the most benefit in these scenarios:

  • High-traffic static file servers: Sites serving many images, CSS files, JavaScript, or downloadable content see reduced filesystem overhead on repeated requests.
  • Networked or slow storage: When files are stored on NFS, CIFS, or other networked filesystems, caching file metadata locally avoids network round trips.
  • Many small files: Serving thousands of small files benefits from reduced per-request syscall overhead.
  • CDN or edge servers: Edge nodes serving cached content benefit from reduced latency when the open file cache eliminates filesystem lookups.

Open file cache may not provide noticeable benefits in these cases:

  • Low-traffic sites: If your site receives few requests, the cache may not be populated frequently enough to help.
  • Dynamically generated content: PHP, Python, or other application servers generate responses at runtime; the open file cache only helps with static files Nginx serves directly.
  • Development environments: Frequently changing files can cause stale content issues, making caching counterproductive.

Additional Nginx Performance Optimizations

Open file cache works alongside other Nginx optimizations. Consider enabling these related features for better overall performance:

Conclusion

Enabling open file cache in Nginx reduces the filesystem overhead of serving static files by keeping file descriptors and metadata in memory. The four directives control cache size, eviction policy, revalidation frequency, and error caching. For most production servers, the default settings with a cache size of 10,000 entries and 60-second validation intervals provide a good balance between performance and freshness. After applying these settings, monitor your server’s response times and adjust the values if you need to cache more files or respond faster to file changes.

Leave a Comment