One of the significant uses of the NGINX server is serving static content. NGINX excels in this area due to its event-driven model and capability to use the system calls such as sendfile.
In this tutorial, we will walk through the “sendfile” directive in NGINX. This “sendfile” directive transfers the data from one file descriptor to another which improves the efficiency of static file serving.
Requirements:
Before we start, you should have the following:
- A basic understanding of Linux terminal commands.
- Installed NGINX on your server.
- Root or sudo access to your server.
NGINX Sendfile
Sendfile is a system call that allows the applications to send the data from a file directly to a TCP connection, bypassing the userspace. It’s an efficient way to serve the static files because it reduces the number of context switches and data copies between the kernel and userspace.
Check the Sendfile Support
The first step is to check your kernel’s support for the sendfile system call. Most systems support this feature, but you can run the following command to verify it:
The command should return the following:
Enable the Sendfile in NGINX
Edit the NGINX configuration file using your favorite text editor. Typically, the NGINX onfig file is located in /etc/nginx/nginx.conf.
Locate the “sendfile” directive in the HTTP block. If it’s not there, you can add it as shown in the following:
sendfile on;
...
}
However, if the sendfile directive exists but is turned off (sendfile off;), change its value to on.
Save the configuration file and exit your text editor.
Restart NGINX
Once you made the changes, verify the server configuration using the following command:
Output:
Finally, restart NGINX:
Conclusion
This tutorial walked you through the NGINX “sendfile” directive which is a powerful tool that can significantly improve the efficiency of serving static files.