Chapter 1. Basics

1.0 Introduction

To get started with NGINX Open Source or NGINX Plus, you first need to install it on a system and learn some basics. In this chapter, you will learn how to install NGINX, where the main configuration files are located, and what the commands are for administration. You will also learn how to verify your installation and make requests to the default server.

Some of the recipes in this book will use NGINX Plus. You can get a free trial of NGINX Plus at https://nginx.com.

1.1 Installing NGINX on Debian/Ubuntu

Problem

You need to install NGINX Open Source on a Debian or Ubuntu machine.

Solution

Update package information for configured sources and install some packages that will assist in configuring the official NGINX package repository:

$ apt update
$ apt install -y curl gnupg2 ca-certificates lsb-release \
    debian-archive-keyring

Download and save the NGINX signing key:

$ curl https://nginx.org/keys/nginx_signing.key | gpg --dearmor \
  | tee /usr/share/keyrings/nginx-archive-keyring.gpg >/dev/null

Use lsb_release to set variables defining the OS and release names, then create an apt source file:

$ OS=$(lsb_release -is | tr '[:upper:]' '[:lower:]')
$ RELEASE=$(lsb_release -cs)
$ echo "deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] \
    http://nginx.org/packages/${OS} ${RELEASE} nginx" \
    | tee /etc/apt/sources.list.d/nginx.list

Update package information once more, then install NGINX:

$ apt update
$ apt install -y nginx
$ systemctl enable nginx
$ nginx

Discussion

The commands provided in this section instruct the advanced package tool (APT) package management system to utilize the official NGINX package repository. The NGINX GPG package signing key was downloaded and saved to a location on the filesystem for use by APT. Providing APT the signing key enables the APT system to validate packages from the repository. The lsb_release command was used to automatically determine the OS and release name so that these instructions can be used across all release versions of Debian or Ubuntu. The apt update command instructs the APT system to refresh its package listings from its known repositories. After the package list is refreshed, you can install NGINX Open Source from the official NGINX repository. After you install it, the final command starts NGINX.

1.2 Installing NGINX Through the YUM Package Manager

Problem

You need to install NGINX Open Source on Red Hat Enterprise Linux (RHEL), Oracle Linux, AlmaLinux, Rocky Linux, or CentOS.

Solution

Create a file named /etc/yum.repos.d/nginx.repo that contains the following contents:

[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=0
enabled=1

Alter the file, replacing OS in the middle of the URL with rhel or centos, depending on your distribution. Then, run the following commands:

$ yum -y install nginx
$ systemctl enable nginx
$ systemctl start nginx
$ firewall-cmd --permanent --zone=public --add-port=80/tcp
$ firewall-cmd --reload

Discussion

The file you just created for this solution instructs the YUM package management system to utilize the official NGINX Open Source package repository. The commands that follow install NGINX Open Source from the official repository, instruct systemd to enable NGINX at boot time, and tell it to start NGINX now. If necessary, the firewall commands open port 80 for the transmission control protocol (TCP), which is the default port for HTTP. The last command reloads the firewall to commit the changes.

1.3 Installing NGINX Plus

Problem

You need to install NGINX Plus.

Solution

Visit the NGINX docs. Select the OS you’re installing to and then follow the instructions. The instructions are similar to those of the installation of the open source solutions; however, you need to obtain a certificate and key in order to authenticate to the NGINX Plus repository.

Discussion

NGINX keeps this repository installation guide up-to-date with instructions on installing NGINX Plus. Depending on your OS and version, these instructions vary slightly, but there is one commonality. You must obtain a certificate and key from the NGINX portal, and provide them to your system, in order to authenticate to the NGINX Plus repository.

1.4 Verifying Your Installation

Problem

You want to validate the NGINX installation and check the version.

Solution

You can verify that NGINX is installed and check its version by using the following command:

$ nginx -v
nginx version: nginx/1.25.3

As this example shows, the response displays the version.

You can confirm that NGINX is running by using the following command:

$ ps -ef | grep nginx
root      1738     1  0 19:54 ?  00:00:00 nginx: master process
nginx     1739  1738  0 19:54 ?  00:00:00 nginx: worker process

The ps command lists running processes. By piping it to grep, you can search for specific words in the output. This example uses grep to search for nginx. The result shows two running processes: a master and worker. If NGINX is running, you will always see a master and one or more worker processes. Note the master process is running as root, as, by default, NGINX needs elevated privileges in order to function properly. For instructions on starting NGINX, refer to the next recipe. To see how to start NGINX as a daemon, use the init.d or systemd methodologies.

To verify that NGINX is returning requests correctly, use your browser to make a request to your machine or use curl. When making the request, use the machine’s IP address or hostname. If installed locally, you can use localhost as follows:

$ curl localhost

You will see the NGINX Welcome default HTML site.

Discussion

The nginx command allows you to interact with the NGINX binary to check the version, list installed modules, test configurations, and send signals to the master process. NGINX must be running in order for it to serve requests. The ps command is a surefire way to determine whether NGINX is running either as a daemon or in the foreground. The configuration provided by default with NGINX runs a static-site HTTP server on port 80. You can test this default site by making an HTTP request to the machine at localhost. You should use the host’s IP and hostname.

1.5 Key Files, Directories, and Commands

Problem

You need to understand the important NGINX directories and commands.

Solution

The following configuration directories and file locations can be changed during the compilation of NGINX and therefore may vary based on your installation.

NGINX files and directories

/etc/nginx/

The /etc/nginx/ directory is the default configuration root for the NGINX server. Within this directory you will find configuration files that instruct NGINX on how to behave.

/etc/nginx/nginx.conf

The /etc/nginx/nginx.conf file is the default configuration entry point used by the NGINX daemon. This configuration file sets up global settings for things like worker processes, tuning, logging, loading dynamic modules, and references to other NGINX configuration files. In a default configuration, the /etc/nginx/nginx.conf file includes the top-level http block, or context, which includes all configuration files in the directory described next.

/etc/nginx/conf.d/

The /etc/nginx/conf.d/ directory contains the default HTTP server configuration file. Files in this directory ending in .conf are included in the top-level http block from within the /etc/nginx/nginx.conf file. It’s best practice to utilize include statements and organize your configuration in this way to keep your configuration files concise. In some package repositories, this folder is named sites-enabled, and configuration files are linked from a folder named site-available; this convention is deprecated.

/var/log/nginx/

The /var/log/nginx/ directory is the default log location for NGINX. Within this directory you will find an access.log file and an error.log file. By default the access log contains an entry for each request NGINX serves. The error logfile contains error events and debug information if the debug module is enabled.

NGINX commands

nginx -h

Shows the NGINX help menu.

nginx -v

Shows the NGINX version.

nginx -V

Shows the NGINX version, build information, and configuration arguments, which show the modules built into the NGINX binary.

nginx -t

Tests the NGINX configuration.

nginx -T

Tests the NGINX configuration and prints the validated configuration to the screen. This command is useful when seeking support.

nginx -s signal

The -s flag sends a signal to the NGINX master process. You can send signals such as stop, quit, reload, and reopen. The stop signal discontinues the NGINX process immediately. The quit signal stops the NGINX process after it finishes processing in-flight requests. The reload signal reloads the configuration. The reopen signal instructs NGINX to reopen logfiles.

Discussion

With an understanding of these key files, directories, and commands, you’re in a good position to start working with NGINX. Using this knowledge, you can alter the default configuration files and test your changes with the nginx -t command. If your test is successful, you also know how to instruct NGINX to reload its configuration using the nginx -s reload command.

1.6 Using Includes for Clean Configs

Problem

You need to clean up bulky configuration files to keep your configurations logically grouped into modular configuration sets.

Solution

Use the include directive to reference configuration files, directories, or masks:

http {
  include conf.d/compression.conf;
  include ssl_config/*.conf
}

The include directive takes a single parameter of either a path to a file or a mask that matches many files. This directive is valid in any context.

Discussion

By using include statements you can keep your NGINX configuration clean and concise. You’ll be able to logically group your configurations to avoid configuration files that go on for hundreds of lines. You can create modular configuration files that can be included in multiple places throughout your configuration to avoid duplication of configurations.

Take the example fastcgi_param configuration file provided in most package management installs of NGINX. If you manage multiple FastCGI virtual servers on a single NGINX box, you can include this configuration file for any location or context where you require these parameters for FastCGI without having to duplicate this configuration. Another example is Secure Sockets Layer (SSL) configurations. If you’re running multiple servers that require similar SSL configurations, you can simply write this configuration once and include it wherever needed.

By logically grouping your configurations together, you can rest assured that your configurations are neat and organized. Changing a set of configuration files can be done by editing a single file rather than changing multiple sets of configuration blocks in multiple locations within a massive configuration file. Grouping your configurations into files and using include statements is good practice for your sanity and the sanity of your colleagues.

1.7 Serving Static Content

Problem

You need to serve static content with NGINX.

Solution

Overwrite the default HTTP server configuration located in /etc/nginx/conf.d/default.conf with the following NGINX configuration example:

server {
  listen 80 default_server; 
  server_name www.example.com; 

  location / {
    root /usr/share/nginx/html;
    # alias /usr/share/nginx/html;
    index index.html index.htm;
  }
}

Discussion

This configuration serves static files over HTTP on port 80 from the directory /usr/share/nginx/html/. The first line in this configuration defines a new server block. This defines a new context that specifies what NGINX listens for. Line two instructs NGINX to listen on port 80, and the default_server parameter instructs NGINX to use this server as the default context for port 80. The listen directive can also take a range of ports. The server_name directive defines the hostname or the names of requests that should be directed to this server. If the configuration had not defined this context as the default_server, NGINX would direct requests to this server only if the HTTP host header matched the value provided to the server_name directive. With the default_server context set, you can omit the server_name directive if you do not yet have a domain name to use.

The location block defines a configuration based on the path in the URL. The path, or portion of the URL after the domain, is referred to as the uniform resource identifier (URI). NGINX will best match the URI requested to a location block. The example uses / to match all requests. The root directive shows NGINX where to look for static files when serving content for the given context. The URI of the request is appended to the root directive’s value when looking for the requested file. If we had provided a URI prefix to the location directive, this would be included in the appended path, unless we used the alias directive rather than root. The location directive is able to match a wide range of expressions. Visit the first link in the “See Also” section for more information. Finally, the index directive provides NGINX with a default file, or list of files to check, in the event that no further path is provided in the URI.

Get NGINX Cookbook, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.