Nginx Web Server

The NGINX server is an open source project developed to solve the C10 limit per single server. It is a high-performance web server with caching and reverse proxy support to serve large, high performance websites.

NGINX was first released in 2004 by Igor Sysoev and is now maintained by Nginx, Inc.

Its popularity is mainly due to its ability to handle high traffic loads, scalability, and flexibility of configuration.

High performance and throughput of the NGINX web server allow it to be used as a software load balancer with multiple back-end servers.

Popular websites and online services, including Netflix, Airbnb, Dropbox, and WordPress. Whether you are building a simple website or a complex web application,

NGINX is available for all major operating systems such as CentOS, Debian, Fedora, MacOS, Redhat, Ubuntu and Windows.

I this post on NGINX, I will be providing the basics, and then discuss some advanced performance and security features.

NGINX Basics

Nginx is a multi-faceted web server that can operate as a reverse proxy server, load balancer, HTTP cache, and mail proxy server.

The basics of Nginx include its installation, configuration files, directives, and syntax.

Installing NGINX on FreeBSD, Linux, MacOS, and Windows

Nginx can be installed on FreeBSD, Linux, MacOS, and Windows. The installation process varies depending on the operating system. On Windows, you will download an Installer and use that to install it locally. On the other operating systems there are packages available to install using one of the package managers.

For Windows Install, download Nginx from this link.

On Debian based Linux and Ubuntu used the command below to install.

sudo apt install nginx

On FreeBSD use the pkg command to install Nginx.

pkg install nginx

And finally on MacOS use brew to install Nginx.

brew install nginx

Check out my posts on Installing Nginx and PHP on Windows and Installing Nginx, PHP FPM and MySQL on Ubuntu

For custom builds you first need to download the source code. Second, you must have a development environment setup to start a build and create a custom binary.

NGINX Configuration Files

Nginx web server provides the ability to use one or more websites. Using the configuration files you can change the default server behavior and setup Virtual Hosts to service single or multiple domains.

The main configuration file nginx.conf is located at /etc/nginx/nginx.conf for Linux based systems and in the path, {Nginx Install Path}\conf\nginx.conf.

Nginx configuration uses blocks to manage related configurations. Within the blocks, directives are used to configure block level variables.

Following are some key blocks used by Nginx:

  • http: root level directive for all server blocks.
  • server: Used to create configuration for a domain:port combination for site serving.
  • location: This directive is used to define path(s) and related properties for a domain.

NGINX Directives

Directives are used to configure the behavior of the server. Directives can be specified in the main configuration file or in individual configuration files.

Some common directives are:

  • index: Name of the index file. (index.html, index.php or any other name an admin may define).
  • server_name: domain name.
  • listen: Port the Domain name with serve. (Usually 80 or 443)
  • access_log: Path to the server access log file.
  • root: Specifies the root folder to serve static files from.
  • proxy_pass: Used with Nginx for setting up a reverse proxy server.

There are many more directives available to fine-tune the server configuration. Read the documentation for complete details.

NGINX Configuration File Syntax

The block syntax used in Nginx configuration files use curly braces {}, to group related configurations. Within the blocks are directives which is a value followed by an argument, ending with a semicolon (;).

Note: There can only be 1 single directive per line.

Lines beginning with a # are ignored and is commonly used for adding comments.

server {
    location / {
        root /data/www;
    }

    location /images/ {
        root /data;
    }
}

In the example shown above you will find 3 blocks (lines 1, 2, 6).

NGINX Features

Nginx is a flexible and powerful web server that offers a range of features to created scalable architectures for web applications.

Let’s review some of these features.

Nginx reverse proxy and cache with load balancing.
Nginx reverse proxy and cache with load balancing.

NGINX as a Reverse Proxy

Many companies configure Nginx to act as a reverse proxy server. In the reverse proxy role, Nginx acts as a front end for other applications. All incoming traffic is intercepted by Nginx and then forwarded to the backend for processing. The result when received from the backend is then sent back to the original client requesting the requested resource.

Reverse proxy can be used to prevent direct access to a backend server.

Nginx can also perform health checks on backend servers, ensuring that requests are only forwarded to healthy servers.

Using NGINX For Caching Content and Websites

Building on top of the reverse proxy feature, Nginx also adds the ability to cache the results or the backend server response. This ability to cache the responses allow Nginx to complete incoming client requests without connecting to the backend server. This provides the ability to serve many more client requests when compared against sending each request to backend for processing.

Nginx can use disk or memory based caching schemes.

Content can be cached based on URL, HTTP request methods (GET, POST…), or HTTP response status codes.

Load Balancing with NGINX

Nginx’s load balancing features allow it to distribute incoming requests across multiple backend servers, which can help improve the performance and scalability of the web infrastructure.

Nginx provides many load balancing algorithms, such as round-robin, IP hash, and least connections.

TIP: Use NGINX as a reverse proxy with caching and load balancing features, allows to build highly scalable and responsive web application infrastructure.

SSL Termination with NGINX

Use Nginx to terminate SSL/TLS connections. What this means is that the data encryption ends at the Nginx server and it forwards the traffic to the backend server over an encrypted connection. Not using encryption for the backend transport layers reduces the load on the servers and improves the overall performance.

One thing to keep in mind is that in certain cases there may be legal requirements to keep all communication channels encrypted. another factor to consider when using SSL termination is that the backend servers should be within the internal network and not exposed to the public internet.

Advanced HTTP Support

Nginx supports the HTTP/2 protocol, which offers various performance improvements over the older HTTP/1.x protocol. HTTP/2 supports multiplexing, allowing multiple requests to be sent over a single connection, reducing the overhead of establishing and maintaining multiple connections.

Nginx also supports HTTP/3 features. Checkout Nginx+Quick website for more deta

NGINX WebSocket Support

Nginx supports WebSocket connections, which allow real-time communication between clients and servers. WebSocket connections are used in chat applications, real-time gaming, and trading applications that provide real-time quotes.

The use case for WebSocket connections is for applications that require low-latency communication.

Rate Limiting with NGINX

Using the Nginx HTTP rate limiting module, you can configure Nginx to control the number of incoming connections and requests to an Nginx instance.

Rate limiting feature can be used to limit access to the websites hosted on an Nginx server to help prevent abuse.

Content Compression with NGINX

Nginx can compress content before sending it to clients, reducing the amount of data that needs to be transmitted and improving the overall performance of your web infrastructure. This is done using the Nginx Gzip compression module. The Gzip module supports various compression algorithms, such as gzip and Brotli.

Advanced Features of NGINX

NGINX provides advanced features using modules to offer additional capabilities for the user of their software. Let’s look at some selected features.

NGINX GeoIP Module

Nginx’s GeoIP module allows the ability to block or redirect traffic based on the geographic location of the client.

This is useful for blocking traffic from certain countries or regions from accessing your website. You can also use this feature to redirect clients to a localized version of your website.

Real Time Logging

Nginx can stream access logs in real-time, allowing you to monitor traffic and troubleshoot issues as they occur. This can be especially useful for high-traffic sites where logs can grow quickly and become difficult to manage.

Nginx has many advance features that are built in and more that can be added using modules. I will get more into available modules for NGINX later in this post. You can also click the Nginx modules and get more details.

NGINX Security

Security is the most critical need of an infrastructure serving clients over the public internet. Nginx, does not disappoint here as it can help protect an application from various threats, such as, DDoS attacks, brute force attacks, and malicious traffic.

Let’s explore some key security features of Nginx.

NGINX SSL/TLS Configuration

With the use of SSL certificates, Nginx offers secure SSL/TLS connections over HTTP, creating HTTPS tunnels allowing encrypted communications between a client and the server.

Nginx also supports OCSP stapling, which allows the server to provide clients with up-to-date revocation information for SSL/TLS certificates.

What is OCSP stapling?

OCSP stapling is a mechanism used in the Transport Layer Security (TLS) protocol to improve the performance and security of a SSL/TLS connection.

Access Control

You can restrict access to your web server files and other resources by using the access control features of Nginx.

You can restrict access based on an IP address, HTTP header, or HTTP method.

Use Nginx authentication and authorization controls to require credentials before allowing access to protected resources.

Content Filtering

Nginx can further limit access to URIs based on various criteria such as a MIME type or file extension. Using content filtering provides the ability to restrict the uploading and downloading of executables and scripts.

Using NGINX as a Firewall

Nginx can be configured as a firewall to allow, block and filter incoming traffic. You can configure these rules to work based on an IP address or using any of the HTTP headers, such as a user agent.

NGINX Performance Tuning

Tuning a web server for getting maximum use can be a complicated process as it depends on many factors. Some are internal that can be fine tuned using attributes while others are external to a web server.

In this section, I will go over some of the server attributes of Nginx that should always be used based on usage to improve response times and increase server throughput.

Let’s look at some relevant Nginx configuration attributes.

Worker Processes

Nginx is an event-based web server. But it also uses worker processes to handle incoming requests. The number of worker processes can be configured based on the available system resources, mostly the number of CPU cores, available drives and load pattern.

Increasing the number of worker processes can help improve Nginx’s ability to handle concurrent connections.

Attribute name: worker_processes

Connections

The number of connections is the maximum number of connections that can be handled by a single Nginx worker thread.

Attribute name: worker_connections

Use this attribute to optimize the server’s performance and ability to serve high traffic loads.

worker_processes 2;

events {
    worker_connections 512;
}

http {

    server {
    }
}
Nginx Configuration using work_processes and worker_connections attributes.

Buffering

Nginx buffering is a feature that allows Nginx to temporarily store and process incoming client requests and server responses.

With the default configuration, Nginx uses small buffers to store data before sending the response back to the client. You can change the size of the buffer using proxy_buffer_size and proxy_buffers parameters.

Note: Making the buffers really large does not necessarily increase response times. In many cases, it may reduce the experience of a user accessing web resources. Set these values based on the type of content being served.

Caching

By storing frequently accessed content in a memory or disk cache will reduce the load on the backend server. Tuning cache parameters can help optimize the server’s performance and improve response times.

Use the proxy_cache_path and proxy_cache directives to configure Nginx caching.

http {
    # Define the path where cached data will be stored
    proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m inactive=60m;

    # Define the default cache configuration
    proxy_cache_key "$scheme$request_method$host$request_uri";
    proxy_cache_valid 200 60m;
    proxy_cache_valid 404 1m;
    
    # Other HTTP configuration directives here...
    
    server {
        # Define the cache configuration for a specific location
        location / {
            # Enable caching for this location
            proxy_cache my_cache;
            proxy_cache_bypass $http_pragma;
            proxy_cache_revalidate on;
            
            # Other location-specific configuration directives here...
        }
    }
}

In the example shown above a disk cache is set up with cache timeout for HTTP response codes 200 and 404.

Once the cache is configured, the server block uses the proxy_cache directive to use this specific cache location.

NGINX Use Cases

Following are the most common use cases for Nginx.

  • Reverse Proxy
  • Fast and scalable static content web server
  • Content delivery network (CDN)
  • API Gateway.

Who Uses Nginx?

CloudFlare, Fastly, and MaxCDN provide some of the best examples of Nginx used in large scale CDNs.

Netflix also uses Nginx to serve most of its streaming content utilizing AWS services.

Above are some examples where Nginx is being used to provide large scale web services. But there are other companies using Nginx as well. As a matter of fact, almost all of the Fortune 1,000 companies use Nginx in some capacity.

Even this website uses Nginx in front of the static content server and the API server.

Summary

Nginx is a powerful and versatile web server that can be used to serve static content or to host complex high performance web applications.

Nginx’s basic key features include reverse proxying, load balancing, caching, and content compression while advanced features, such as HTTP/2 Server Push, WebSocket Load Balancing, and Real-Time Logging can be used to optimize the performance and scalability of most application architectures.

Using the information provided in this post you should be able to evaluate Nginx web server features against your requirements to determine if it is the right solution for you.


Frequently Asked Questions

What is NGINX?

Nginx is a web server software that operates as a reverse proxy server, load balancer, HTTP cache, and mail proxy server. It was designed to handle high-traffic loads efficiently and is widely used in various applications.

Is NGINX a Web Server?

NGINX is a free, open-source, high-performance web server and can also be configured as a reverse caching proxy server. NGINX is also used to proxy connections to email servers supporting the IMAP and POP3 protocols.

NGINX is known for its high performance and stability with low consumption of resources. Its primary use is as a load balancer with caching capability serving static files with high throughput.

Is NGINX Free?

Nginx generally is available as a free open source web server with an extensive set of documentation available online.

But a paid version of Nginx does exist and is called Nginx+. This version comes with paid support options and is used widely.

Generally, the feature set is the same, but Nginx+ provides added features and additional modules to provide additional configuration options to their clients.

How Do I Install Nginx?

Nginx can be installed on FreeBSD, Linux, MacOS and Windows.

Check out my posts on Installing Nginx on Windows and Installing Nginx on Ubuntu

Can Nginx be used as a reverse proxy server?

Nginx can act as a reverse proxy server, forwarding requests from clients to backend servers. Check my post on using Nginx as a reverse server.

Can Nginx Cache Content?

Nginx’s does allow caching to store frequently requested content in memory thereby reducing the load on backend servers.

Read my post on Nginx Caching.

Can Nginx be used in the Cloud and with Docker?

Nginx can be used in cloud environments such as Amazon Web Services (AWS) and Microsoft Azure.

Nginx can also be used with Docker and other containerized applications.

Which Comapnies Provide Commercial Support Services for NGINX?

Nginx, Inc., which develops the Nginx web server, also has a commercial version of the server called Nginx Plus.

Nginx Plus comes with 24/7 support from Nginx, Inc., including phone and email support.

Note: Recently Nginx, Inc. was bought by F5 in March 2019.

Can I use Nginx for Large Media Files?

NGINX is great at serving static files with high throughput. Netflix serves large media files using NGINX via the asynchronous sendfile() system call. You can read the complete article on the Netflix tech blog.