How to Enable Open File Cache in Nginx for Better Performance
To enable
open_file_cache in Nginx, add the directive inside the http, server, or location block in your configuration file. Configure parameters like max, inactive, and min_uses to control caching behavior, then reload Nginx to apply changes.Syntax
The open_file_cache directive enables caching of file descriptors to improve performance by reducing file open/close operations. It accepts three parameters:
- max: Maximum number of cached files.
- inactive: Time in seconds to keep unused cached files before removal.
- min_uses: Minimum number of uses before a file is cached.
Example syntax:
nginx
open_file_cache max=1000 inactive=20s min_uses=2;
Example
This example enables open file cache globally in the http block. It caches up to 1000 files, keeps them for 20 seconds if unused, and caches files used at least twice.
nginx
http {
open_file_cache max=1000 inactive=20s min_uses=2;
server {
listen 80;
server_name example.com;
location / {
root /var/www/html;
index index.html;
}
}
}Common Pitfalls
Common mistakes when enabling open_file_cache include:
- Setting
maxtoo low, causing frequent cache evictions. - Using too short
inactivetime, which reduces cache effectiveness. - Not reloading Nginx after configuration changes.
- Enabling cache in inappropriate contexts (e.g., inside
locationblocks that do not serve static files).
Always test configuration with nginx -t before reloading.
nginx
## Wrong way (too low max and no reload):
http {
open_file_cache max=10 inactive=5s min_uses=1;
}
## Correct way:
http {
open_file_cache max=1000 inactive=20s min_uses=2;
}
# Then run: nginx -t && nginx -s reloadQuick Reference
| Directive | Description | Example Value |
|---|---|---|
| open_file_cache | Enables file descriptor caching | max=1000 inactive=20s min_uses=2 |
| max | Max cached files | 1000 |
| inactive | Cache timeout for unused files | 20s |
| min_uses | Minimum uses before caching | 2 |
Key Takeaways
Enable open_file_cache inside http, server, or location blocks to cache file descriptors.
Set max, inactive, and min_uses parameters to control cache size and duration.
Always test configuration with nginx -t before reloading to avoid errors.
Avoid setting max too low or inactive too short to maintain cache effectiveness.
Reload Nginx after changes to apply the new open_file_cache settings.