Nginx

Nginx Sendfile Directive

NGINX (pronounced as “engine x”) is a free, open-source, high-performance HTTP server, reverse proxy, and IMAP/POP3 proxy server. It was created by Igor Sysoev in 2002, primarily to address the C10K problem – the difficulty that servers had with handling numerous concurrent connections (around 10,000 and more). NGINX strongly focuses on high concurrency, high performance, and low memory usage which makes it suitable for high-traffic websites.

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:

  1. A basic understanding of Linux terminal commands.
  2. Installed NGINX on your server.
  3. 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:

grep SENDFILE /boot/config-$(uname -r)

The command should return the following:

CONFIG_SENDFILE=y

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.

sudo vim /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:

http {
    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:

sudo nginx -t

Output:

nginx: configuration file /etc/nginx/nginx.conf test is successful

Finally, restart NGINX:

sudo systemctl 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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list