How to Enable sendfile in Nginx for Faster File Serving
To enable
sendfile in Nginx, add the directive sendfile on; inside the http, server, or location block of your Nginx configuration file. This allows Nginx to use efficient file transfer methods to speed up serving static files.Syntax
The sendfile directive controls whether Nginx uses the operating system's zero-copy method to send files directly from disk to the network socket.
sendfile on;enables this feature.sendfile off;disables it.- You can place this directive inside
http,server, orlocationblocks.
nginx
sendfile on;
Example
This example shows how to enable sendfile globally in the http block of the Nginx configuration. It improves performance when serving static files like images or HTML.
nginx
http {
sendfile on;
server {
listen 80;
server_name example.com;
location / {
root /var/www/html;
index index.html;
}
}
}Common Pitfalls
Some common mistakes when enabling sendfile include:
- Not restarting or reloading Nginx after changing the config, so changes don't apply.
- Using
sendfile on;with network file systems (NFS) can cause stale data issues. - Forgetting to check file permissions;
sendfilewon't fix permission errors.
Always test your configuration with nginx -t before reloading.
nginx
## Wrong: sendfile off disables zero-copy
sendfile off;
## Right: enable sendfile for better performance
sendfile on;Quick Reference
| Directive | Description | Default |
|---|---|---|
| sendfile | Enables zero-copy file transfer | off |
| tcp_nopush | Optimizes packet sending with sendfile | off |
| tcp_nodelay | Controls packet delay for small packets | on |
Key Takeaways
Enable sendfile with 'sendfile on;' inside the http, server, or location block.
Restart or reload Nginx after changing the configuration to apply changes.
Avoid using sendfile with network file systems like NFS to prevent stale data.
Always test your Nginx config with 'nginx -t' before reloading.
sendfile improves static file serving performance by using zero-copy transfers.