Enable Nginx open_file_cache for Static Files

Enable Nginx open_file_cache for local static files. Covers directive defaults, safe placement, reload checks, and tuning.

Last updatedAuthorJoshua JamesRead time6 minGuide typeNginx

Repeated static-file requests can waste time on the same filesystem checks: open the file, confirm it still exists, read its size, and check its modification time. Nginx open_file_cache reduces that overhead by keeping file descriptors, file metadata, directory existence checks, and optional lookup errors in memory between requests.

Enable open_file_cache in Nginx when your server repeatedly serves images, CSS, JavaScript, downloads, or other static assets from local disk. It is not a response-body cache, so it does not replace proxy_cache, fastcgi_cache, browser cache headers, or a CDN. It only helps with the filesystem work Nginx performs while serving local files directly.

Understand Nginx open_file_cache Directives

The open_file_cache directive and its companion directives are part of the Nginx HTTP core module. The official Nginx documentation allows these directives in the http, server, and location contexts, which means you can apply one policy globally, per virtual host, or only for selected paths.

The Nginx open_file_cache directive caches open file descriptors, file size and modification time, directory existence, and file lookup errors when error caching is enabled. It does not cache file contents or send HTTP cache headers to browsers.

Choose the Right Nginx Cache Layer

Static-file caching can mean several different Nginx features. Use open_file_cache when the repeated work is filesystem lookup and file opening on the origin server. Use a different cache layer when the repeated work is browser downloads, upstream response generation, or PHP/FastCGI execution.

Reader NeedUseWhat Changes
Reduce repeated local filesystem lookups for static filesopen_file_cacheKeeps file descriptors, metadata, directory checks, and optional lookup errors in worker memory.
Tell visitors’ browsers to reuse CSS, JavaScript, fonts, and imagesbrowser caching for static assets in NginxSends response headers such as Cache-Control or expires; it does not keep files open on the server.
Serve repeated upstream responses from Nginx instead of the backendNginx proxy cacheStores response bodies on disk with proxy_cache_path and activates them with proxy_cache.

Review open_file_cache Directive Defaults

DirectiveDefaultContextPurpose
open_file_cacheoffhttp, server, locationEnables the cache, sets the maximum entry count with max, and optionally sets the inactive eviction window.
open_file_cache_valid60shttp, server, locationSets how often Nginx revalidates cached entries against the filesystem.
open_file_cache_min_uses1http, server, locationSets how many accesses an entry needs during the inactive window to remain cached.
open_file_cache_errorsoffhttp, server, locationControls whether lookup errors such as missing files or permission failures are cached.

For the complete directive syntax, see the official Nginx open_file_cache reference. If you enable open_file_cache without an inactive value, Nginx uses 60 seconds. Pay close attention to the context column, because placing these directives at the top level of nginx.conf, outside http, causes a syntax-test failure.

Enable Nginx open_file_cache

Confirm the Active Nginx Configuration Path

Confirm which configuration file Nginx currently reads before backing it up. Package-managed Linux installs usually report /etc/nginx/nginx.conf, while source builds or custom prefixes can use another path.

sudo nginx -t

The first line identifies the active configuration file:

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

Back Up the Current Nginx Configuration

Back up the active configuration before changing a live server. Replace /etc/nginx/nginx.conf in the backup command if the syntax test reported a different path.

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

On production servers, keep the backup until the syntax test passes, the reload succeeds, and normal traffic checks look clean. A failed reload usually leaves existing workers on the old configuration, but a later restart with the same broken file can take the site offline.

Add open_file_cache to the Nginx http Block

Edit the same configuration file you backed up. Replace the path when the syntax test reported a custom prefix:

sudo nano /etc/nginx/nginx.conf

Add these directives inside the existing http block. The values create a moderate global cache for static-file metadata and lookup results:

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

The max=10000 setting caps the cache at 10,000 entries. The inactive=30s setting removes entries that are not reused within 30 seconds, while open_file_cache_valid 60s controls how often Nginx checks whether cached metadata is still current.

Review the Nginx open_file_cache Placement

This partial http block shows correct placement. Do not replace your full configuration with this snippet; copy only the open_file_cache directives into your existing file.

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

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

    sendfile on;

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

The snippet includes sendfile on; because it is common in static-file configurations. It handles file transfer differently from open file cache: sendfile changes how file data moves from disk to the network socket, while open_file_cache reduces repeated metadata and descriptor work. For that separate optimization, see how to enable the Nginx sendfile directive.

Tune Nginx open_file_cache for Static Files

Start with the global settings above, then tune by traffic pattern. Higher values are useful only when the server repeatedly touches enough files to keep the cache warm.

High-Traffic Static Assets

For an image-heavy site, download mirror, or CDN edge node with a large working set, increase the entry count and use a longer inactive window:

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

This keeps frequently reused entries around longer and avoids filling the cache with one-off requests. The tradeoff is slower recognition of file changes because Nginx waits longer before revalidating cached metadata.

Fast-Changing Static Files

For staging sites, build previews, or directories where assets change frequently, keep the validation interval short and avoid caching lookup errors:

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

If files change constantly, disable the feature for that environment or location instead:

open_file_cache off;

Static Location Only

When one virtual host mixes static assets with proxied or dynamic application routes, place open file cache on the static location instead of the whole server block:

server {
    server_name example.com;
    root /var/www/example.com/public;

    location /assets/ {
        open_file_cache max=20000 inactive=60s;
        open_file_cache_valid 60s;
        open_file_cache_min_uses 2;
        open_file_cache_errors on;
    }

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }
}

This pattern keeps the optimization focused on files Nginx serves directly. It does not speed up upstream responses from proxy_pass, fastcgi_pass, or application code that generates content at runtime.

Verify Nginx open_file_cache Configuration

Test Nginx Syntax Before Reloading

Retest Nginx syntax after editing and before applying the change:

sudo nginx -t

A successful syntax test prints these two lines:

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

Reload Nginx After the Syntax Test

Reload Nginx after the syntax test passes. A reload applies the new configuration without intentionally dropping active connections, and Nginx re-reads directive values only after a reload or restart.

sudo systemctl reload nginx

On non-systemd systems, send Nginx a reload signal directly:

sudo nginx -s reload

For systemd-based Linux servers, confirm the service is still active:

systemctl is-active nginx
active

Confirm open_file_cache Appears in Nginx Configuration

Nginx does not expose a built-in open file cache hit-rate command. Confirm the merged configuration Nginx parses instead; the grep -E filter keeps the output focused on file-cache lines.

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

Relevant output includes:

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

For deeper diagnostics, compare request latency, disk activity, and error logs before and after the change. Tools such as strace can show fewer repeated filesystem calls for the same hot file, but tracing a production worker adds overhead and should be brief.

Troubleshoot Nginx open_file_cache Issues

Fix open_file_cache Directive Is Not Allowed Here

If sudo nginx -t reports this error, the directive is in the wrong context:

nginx: [emerg] "open_file_cache" directive is not allowed here in /etc/nginx/nginx.conf:15
nginx: configuration file /etc/nginx/nginx.conf test failed

Move the directive into the http, server, or location block. Do not place it beside top-level directives such as worker_processes, pid, or error_log.

sudo nginx -t

The context error is fixed when the syntax test reaches test is successful.

Fix Missing Semicolons in Nginx open_file_cache Lines

A missing semicolon can make Nginx treat the next line as extra arguments to the previous directive:

nginx: [emerg] invalid number of arguments in "open_file_cache" directive in /etc/nginx/nginx.conf:28
nginx: configuration file /etc/nginx/nginx.conf test failed

Check that every directive ends with a semicolon:

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

Retest Nginx after saving the corrected line:

sudo nginx -t

Clear Nginx open_file_cache After File Changes

If a newly created file still returns a cached lookup error, or a replaced static file does not appear immediately, wait for open_file_cache_valid to pass or reload Nginx. Reloading clears the open file cache and lets workers rebuild it from fresh lookups.

sudo nginx -t

Reload Nginx only after the syntax test succeeds:

sudo systemctl reload nginx

If this happens often during deployments, lower open_file_cache_valid, turn open_file_cache_errors off for fast-changing paths, or disable open file cache in staging and preview environments.

Avoid Oversizing Nginx open_file_cache

A very large max value keeps more descriptors and metadata available, but it also increases memory and file-descriptor pressure. If the server has limited RAM or low file limits, reduce max before changing broader worker or operating-system limits.

sudo nginx -T 2>/dev/null | grep -E 'open_file_cache|worker_rlimit_nofile|worker_connections'

Review the printed values together. A high open_file_cache max setting should make sense beside your worker count, connection target, and the number of hot files your site actually serves.

Open file cache works best when it is one part of a static-file delivery plan. These related Nginx guides cover separate layers of the request path:

Conclusion

Nginx open_file_cache is in place when the syntax test passes, the server reloads cleanly, and nginx -T shows the expected directives in the merged configuration. Keep the cache focused on static files that are reused often, then tune max, inactive, and open_file_cache_valid around freshness, memory use, and deployment frequency. If the remaining bottleneck is client re-downloads or upstream generation, move to browser cache headers, proxy cache, or FastCGI cache instead of increasing open file cache values.

Share this guide

Help another Linux user troubleshoot faster

Share this guide with someone troubleshooting Linux systems or saving it for later.

Follow LinuxCapable

Want more LinuxCapable guides in Google?

Add LinuxCapable as a preferred source so Google can show our tutorials more often in Top Stories and mark them as preferred in AI Mode and AI Overviews when relevant.

Add LinuxCapable as a preferred source on Google
Search LinuxCapable

Need another guide?

Search LinuxCapable for package installs, commands, troubleshooting, and follow-up guides related to what you just read.

Found this guide useful?

Support LinuxCapable to keep tutorials free and up to date.

Buy me a coffeeBuy me a coffee
Before commenting, please review our Comments Policy.
Formatting tips for your comment

You can use basic HTML to format your comment. Useful tags currently allowed in published comments:

You type Result
<code>command</code> command
<strong>bold</strong> bold
<em>italic</em> italic
<a href="https://example.com">link</a> link
<blockquote>quote</blockquote> quote block

Add to the discussion

Questions, fixes, command output, and version notes help keep this guide current.

Verify before posting: