Nginx – Installing Nginx

How to install Chocolatey on Windows 10

You don’t learn to walk by following rules. You learn by doing, and by falling over.

—Richard Branson

Based on your requirements, you can choose to download the precompiled packages or compiled binaries with their components from the Nginx website. If the basic and default set of binaries do not suit your needs, you can choose to download the packages from source and compile it yourself. Both the methods have its pros and cons, and in this chapter you will learn the details in a step-by-step manner. Quite often, you will need to use modules that are not a part of the default setup. In such cases, there is no other way than to compile the binaries accordingly.

Before you start your first deployment of Nginx, you will need to prepare your environment to perform the steps mentioned in this chapter. In today’s world, there are a variety of choices when it comes to configuring your infrastructure. For ease of demonstration and cross-platform support, we have chosen to go with VirtualBox
for virtualization, and two famous Linux distributions of the Fedora (CentOS) and Debian (Ubuntu) family. We will make sure to provide you the commands for each distros so you can practice on either of them.

Preparing Your Environment

Here is what is required:

  • A spare physical machine or virtualization software like VirtualBox. You can download Oracle VirtualBox

  • Based on your choice, you can download either or both of the Linux distributions CentOS
    or Ubuntu Server

  • Download CentOS

    or Ubuntu Server from
    . You can also download the ready-to-use VirtualBox VM images from
    . The server versions used in this book are CentOS 7 and Ubuntu Server 14.04


  • For a detailed step-by-step direction to install and configure CentOS on VirtualBox, you can visit

  • Once your VMs are up and running, the first step is to update the packages that are installed on the server by default. You will require root access to update the packages. The steps to update the packages are the following:

  • On CentOS:

    # su -
    # yum update
    On Ubuntu:
    # sudo apt-get update
    # sudo apt-get upgrade
  • You will also need some basic utilities on the servers to enable you to perform steps mentioned throughout this book. Again you will require root access to install these packages.

  • On CentOS:

    Install Lynx (a text based browser):
    # yum install lynx
    Install Nano (a text editor in case you are not comfortable using vi):
    # yum install nano
    Install wget (a text based downloader that will help download files):
    # yum install wget
    Install ssh (a secure shell to sllow remote login):
    # ssh is installed by default on CentOS

Since you will find many different configuration steps, it is better to save a snapshot of the server. This way, you can play around and revert back safely if anything goes wrong. Open VirtualBox, click the server name, change the tab by clicking the Snapshots button, and click the Camera button. For the purpose of this book, a snapshot is created called Basic.

On Ubuntu                              :

Install Lynx:
# sudo apt-get install lynx

Install Nano:
# nano is installed by default on Ubuntu

Install wget:
# wget is installed by default on Ubuntu

Install ssh:
# sudo apt-get install ssh

Installing Nginx Using Pre-Built Packages

Using Package Manager is the easiest way of installing, updating, upgrading, and removing software packages in Linux. You can download the package from the source by adding the Nginx repository configuration in the repository files on the server.

Nginx product releases are of two types: namely, stable (even version numbers) and mainline or development (odd version numbers). The “stable” versions
are tried and tested versions. It consists of major bug fixes but no new features are added in the stable version. The “mainline” version includes new features and bug fixes and usually is good for testing future versions of the product. In our examples we will be using the stable version but the steps to implement and configure mainline version
is the same.

Install Nginx Pre-Built Package

In this section, you will learn about installing Nginx on two different distros of Linux, namely, CentOS and Ubuntu. It is recommended that you follow along.

On CentOS

  • Login as root, or open the terminal window and use su to change to root user.

  • Add Nginx repository to the server repository list. There are two ways of performing this step:

    Method 1:

    • Create the Nginx repository file in the yum.repos.d directory and then add the repository configuration by editing the nginx.repo file.

    # nano /etc/yum.repos.d/nginx.repo
    • Add the below text in nginx.repo file


    name=nginx repo
    • Save the file.

    Method 2:

    • Download the nginx-release package from Nginx servers.

    # wget
    • Now install the Package Manager repository.

    # rpm –Uvh nginx-release-centos-7-0.el7.ngx.noarch.rpm
  • Now that the package repository is in place, you can install Nginx using this command:

    # yum install nginx
  • You can verify the Nginx installed version using the –v command option:

    # nginx –v
    nginx version: nginx/1.8.0 (expected output)

On Ubuntu Server

Ubuntu PPA
, which is maintained by volunteers, has Nginx in their package repository list and may include some additional modules, but it is not the latest version as what is found on
. To ensure that you have the latest version installed on your server, you will need to add the Nginx repository in the sources.list file.

  1. Open terminal window and open the sources.list file using the command

    sudo nano /etc/apt/sources.list
  2. You can add the Nginx repository links at the bottom of the file. Scroll down to the very bottom of the file and add the two lines below


    deb trusty nginx
    deb-src trusty nginx
  3. Save the file.

  4. Now you can download the package lists from the repositories and update them with the information for the newest versions of the packages and their dependencies. You can do that by typing the following command:

    sudo apt-get update
  5. You will get the following error regarding the missing signature key. It is happening because gpg is trying to sign the nginx release and check its signature. But the signing key is missing on the server and hence gpg is not able to validate the nginx package:

    Reading package lists... Done
    W: GPG error: trusty Release: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY ABF5BD827BD9BF62
  6. Download and add the nginx signature key using the command below:

    # wget
    # sudo apt-key add nginx_signing.key
  7. Now try re-synchronizing the package index from the sources:

    #sudo apt-get update
  8. Now that the package list is updated and indexed, you can install Nginx:

    # sudo apt-get install nginx
  9. You can verify Nginx installed the version:

    # nginx –v

Nginx Folder Structure

It is important to understand how the Package Manager-based Nginx
installation folder structure looks. It will help you to locate the configuration files if you want to make any configuration changes such as changing the user account under which Nginx process executes, enables, or disables mime types for your website; modify FastCGI execution parameters; identify the default document root and error logs directory; or understand where the error logs files and Nginx executable are


  • You can get the complete list of all Nginx configuration details and its version by using the V command option with nginx. Here is a sample output of the command:

    # nginx –V
    nginx version: nginx/1.8.0
    built by gcc 4.8.2 20140120 (Red Hat 4.8.2-16) (GCC)
    built with OpenSSL 1.0.1e-fips 11 Feb 2013
    TLS SNI support enabled
    configure arguments:
    ... output trimmed ...

    The Package Manager-based installation
    installs Nginx under /etc/nginx directory. It installs all necessary configuration files like
    nginx.conf file
    , which has the web server configuration details. It has a mine.types and fastcgi_params file that contains all the mime types that are enabled on the web server and fastcgi configuration details. All these default configurations enable the Nginx server to start:

    # ls –F /etc/nginx/
    conf.d/          koi-utf  mime.types  scgi_params   win-utf
    fastcgi_params   koi-win  nginx.conf  uwsgi_params
  • The Nginx executable nginx is located in the system executable directory /usr/sbin/nginx. Since it is executing using the root user, you will need to be a root user or need to do su or sudo to start or stop the process:

    # ls -l /usr/sbin/nginx
    -rwxr-xr-x. 1 root root 890992 Apr 21 21:06 /usr/sbin/nginx
  • By default, the document root directory is located at /usr/share/nginx/html/. It consists of a sample index.html and 50x.html file. You can deploy your application in the same document root directory and Nginx will serve the content:

    # ls  /usr/share/nginx/html/
    50x.html  index.html
  • The default error files and HTTP logfiles are located at /var/log/nginx/. By default, there are two files: access. logand error. log. You will have to implement some sort of log file rotation mechanism
    such that your logfiles don’t grow up too large. You will learn more about these files and its configuration details in chapter 10.

  • Try Lynx to browse to the http://localhost and you should be presented with the default index page. (If you get an alert saying Unable to connect to remote host, simply start the Nginx server using systemctl start nginx)


    # lynx http://localhost

You can edit the nginx.conf file to make any configuration changes. You have to be a root user or sudo the command to make the changes (i.e., sudo nano /etc/nginx/nginx.conf). You will need to restart nginx processes to ensure the configuration changes takes effect.

You now have a working version of Nginx on the server. In this section you understood the steps required to perform the Package Manager-based Nginx
installation. You also learned what the default Nginx installation directory structure looks like and identified some of the configuration parameters that are available in an nginx.conf file. You will learn about all the configuration details in depth in chapter 5.

Uninstall Nginx

Before you continue with the next section of installing Nginx from source, you would want to remove Nginx that you just installed using Package Manager. The steps to uninstall Nginx are given in this section.

On CentOS

# yum remove nginx nginx-common

On Ubuntu

# sudo apt-get purge nginx nginx-common

The preceding command removes all the traces of Nginx installation. On CentOS, though, the log and cache directories are not deleted, which are located at /var/log/nginx and /var/cache/nginx respectively. You will have to manually remove them.


Uninstalling Nginx using the commands just described does not remove the yum repository nginx.repo and source.lists entry for Nginx. You will have to remove it manually if you do not want Package Manager-based installation.

Downloading Nginx from Source

Installing Nginx is easy as you have seen. However, there are multiple scenarios where you may need extra functionality or drop an existing one. The way Nginx is architected, you cannot make configuration changes and pull in or plug out the modules (as you typically do in Apache or IIS). In these cases, you will need to rebuild Nginx from source.

Another reason why you may want to build from source is when you would like to have a fresh installation of Nginx with all the customization built in. This way, you won’t have to configure Nginx on each of your servers separately.

To configure Nginx with third-party modules, this also requires you to build from source. Sometimes, you may hit a bug and would like to patch your Nginx source code with customization that serves your particular requirement. Overall, it is extremely important that you understand why you need to learn building Nginx from source.

Downloading Nginx

You can download the source code of Nginx by visiting the website
. The stable version available as of this writing is nginx 1.8.0. The package is in GNU zip format (i.e., tar.gz). You can download the package directly on the server using the wget command as shown:

# wget

Extracting the Nginx Archive

After having downloaded the package you will need to extract the nginx-1.8.0.tar.gz. You can unpack the source code directly in your home directory. When you unpack the package, it will by default create the nginx-1.8.0 folder. This is the directory from where you will be compiling and configuring Nginx. To extract the package, type this:

# tar xzf nginx-1.8.0.tar.gz

Understanding the Nginx Source Directory

After the package is extracted you will find some directories and files in the source directory. You will now see what is included in the source directory. Table 2-1 shows the structure of Nginx source code and here is the output of the source directory:

Table 2-1.
The different directories included in the Nginx source


What Is Included


Contains different configuration options, like modules file for modules those will be installed by default, options file that include different configuration options, etc.


Contains Nginx configuration files like nginx.conf and fastcgi.conf.


This file contains all the configuration details and parameters that are required to compile Nginx. The output of the configure file will create a Makefile.


Contains the geo2nginx module.


Contains the default index.html and 50x.html file that will be configured on the root website location.


Contains the source code of nginx, html, mail, etc.


Contains all the manual pages for Nginx.

# ls –al

-rw-r--r--. 1    1001    1001 249124 Apr 21 19:42 CHANGES
-rw-r--r--. 1    1001    1001 379021 Apr 21 19:42
-rw-r--r--. 1    1001    1001   1397 Apr 21 19:41 LICENSE
-rw-r--r--. 1    1001    1001     49 Apr 21 19:41 README
drwxr-xr-x. 6    1001    1001   4096 Sep 26 12:44 auto
drwxr-xr-x. 2    1001    1001   4096 Sep 26 12:44 conf
-rwxr-xr-x. 1    1001    1001   2478 Apr 21 19:41 configure
drwxr-xr-x. 4    1001    1001     68 Sep 26 12:44 contrib
drwxr-xr-x. 2    1001    1001     38 Sep 26 12:44 html
drwxr-xr-x. 2    1001    1001     20 Sep 26 12:44 man
drwxr-xr-x. 8    1001    1001     71 Sep 26 12:44 src                                                                                                                            

Installing Nginx Binaries

Now that you have Nginx downloaded and extracted, you will need compiling tools and dependent packages before you start compiling Nginx. To begin with, you will need to prepare the server with all the compilation tools. Compiling a package requires a GCC compiler

. After compiling you will need a utility, make, that will build all the programs from the source and then finally install the build on the server.


Most of these compilation tools are already available in the CentOS and Ubuntu repositories. When you use the compilers from the repository, it ensures all the dependent packages are installed along with the package. If you choose to go with a different version of GCC compiler, you will have to take care of lot of other dependent packages, which is out of the scope of this book.

Build Tools for Compilation

If you choose to build Nginx according to your requirements, you will need to follow the steps in this section based on your Linux distro.

On CentOS

CentOS with its yum-based package management enables you to install packages individually, like yum install nginx or use the group install option with yum to install a group of packages together.

  • You can list the group of packages by using the group list command option with yum.

    # yum group list
    Sample output of yum group list:
    ... output trimmed ...
    Available Groups:
       Compatibility Libraries
       Console Internet Tools
       Development Tools
       Graphical Administration Tools
       Legacy UNIX Compatibility
    ... output trimmed ...
  • You will need the Development Tools package group to install all the required compilation and build packages. You can check the list of packages that are available in a particular package by using the group info command


    # yum group info "Development Tools"

    Sample output of the group info of Development Tools:

    Group: Development Tools
     Group-Id: development
     Description: A basic development environment.
     Mandatory Packages:
    ... output trimmed ...
  • If you are curious to know about the different packages that are included in the “Development Tools” and their versions, you can use the following command:

    # yum group install "Development Tools" --assumeno
  • You can use the command below to install Development Tools without prompting you for confirmation:

    # yum group install "Development Tools" --assumeyes
  • Once you are done installing the Development Tools, it is always a good idea to run the update command to update your system:

    # yum update

    You can check GCC and Make versions by using the following command:

# gcc --version
gcc (GCC) 4.8.3 20140911 (Red Hat 4.8.3-9)

# make --version
GNU Make 3.82
Built for x86_64-redhat-linux-gnu                    

On Ubuntu

  • To check for a list of packages that are available with Ubuntu, you will need to use this command


    # sudo apt-cache search all | more

    “apt-cache search” command lists all available packages from the repositories added in the /etc/apt/sources.list file. It is different from the “yum group list” command we used in CentOS as “yum group list” lists all the available groups where as “apt-cache search” shows all the packages, not the groups.

  • To install Development Tools in Ubuntu the command is this:

    # sudo apt-get install build-essential
  • “build essential” package contain the list of packages that are essential for building packages on Ubuntu servers. When you install “build-essential” package it will check for all the dependent packages and will install them for you.

  • You must also update the system after the packages are installed to ensure all components are up to date:

    # sudo apt-get update
    # sudo apt-get upgrade
  • You can verify the GCC and Make version:

    # gcc –version
    gcc (Ubuntu 4.8.4-2ubuntu1∼14.04) 4.8.4
    # make –version
    GNU Make 3.81

Install Dependent Packages

With the development components installed and available on the system, you can now start installing the dependent packages that will enable features in the Nginx web server.

PCRE Library

PCRE is an abbreviation of Perl Compatible Regular Expression. PCRE
is used to implement regular expression pattern matching. You will need PCRE to enable using regular expressions when configuring different Nginx directives and the URL Rewrite or HTTP Rewrite module. CentOS and Ubuntu already have a PCRE-compiled version installed on the server. If your server is missing the compiled package, you will need to install both the compiled and development libraries. The command to install is given in the following sections.

On CentOS:
# yum install pcre
Package pcre-8.32-14.el7.x86_64 already installed and latest version

Install the development libraries for PCRE:

# yum install pcre-devel
  pcre-devel.x86_64 0:8.32-14.el7                                                                          
On Ubuntu:
# sudo apt-get install libpcre3
libpcre3 is already the newest version.

Install the development libraries for PCRE

# sudo apt-get install libpcre3-dev


OpenSSL is used to establish a secure channel between the web server and the client over SSL or TLS. You will need OpenSSL libraries for Nginx SSL modules. OpenSSL is installed by default on most of the new build Linux servers. In case your server is missing the package, you can refer to the command below to install OpenSSL.

You can check the version of OpenSSL using the version command. To get detailed information about an OpenSSL configuration and certificate directory you can use –a command with openssl version command:

On CentOS
# yum install openssl
# openssl version –a
OpenSSL 1.0.1e-fips 11 Feb 2013
built on: Mon Jun 29 12:45:07 UTC 2015
platform: linux-x86_64

… output trimmed …

OPENSSLDIR: "/etc/pki/tls"
engines:  rdrand dynamic

Install OpenSSL development libraries:

# yum install openssl-devel

  openssl-devel.x86_64 1:1.0.1e-42.el7.9
On Ubuntu
# sudo apt-get install openssl
# openssl version –a
OpenSSL 1.0.1f 6 Jan 2014
built on: Thu Jun 11 15:28:12 UTC 2015
platform: debian-amd64
... output trimmed ...
OPENSSLDIR: "/usr/lib/ssl"                                                                                                                                                                              

Install development libraries:

# sudo apt-get install libssl-dev

zlib Library

The zlib library is used for compression. Compression is implemented on the web servers to improve data transfer speed and lower bandwidth utilization. Nginx uses zlib libraries in gzip module for compression.

zlib-devel is one of the dependencies of OpenSSL-devel. So, you will have it installed already. To install zlib-devel individually you can use the following command:

On CentOS
# yum install zlib
Package zlib-1.2.7-13.el7.x86_64 already installed and latest version

Development libraries for zlib:

# yum install zlib-devel
Package zlib-devel-1.2.7-13.el7.x86_64 already installed and latest version
On Ubuntu

You can install both the compiled and development libraries using the command below. You can assign multiple packages together to install:

# sudo apt-get install zlib1g zlib1g-dev

Compiling Nginx

Great! You have the server prepared with all the compilation tools. The dependent development packages are installed and configured, too. Next you will be using these to compile Nginx.

Understanding the ./configure Script

The source directory has a
configure file

that is used to scan for all the dependent packages on the server for Nginx. The configure script for Nginx
checks for machine architecture, defines the Nginx root directory ( /usr/local/nginx by default), threads, modules, and various different configuration and temporary paths. It will then create a Makefile that contains various steps that need to be taken. To have a closer look at what are different configuration parameters available with the configure script for Nginx you will need to use –help option. If you have been following the instructions in this book, ensure that you are in the nginx-1.8.0 directory before you run this command. You can use
pwd command
to know where you are. Below is a sample output of the configure –help:

# ./configure --help

  --help                             print this message

  --prefix=PATH                      set installation prefix
  --sbin-path=PATH                   set nginx binary pathname
  --conf-path=PATH                   set nginx.conf pathname
  --error-log-path=PATH              set error log pathname
  --pid-path=PATH                    set pathname
  --lock-path=PATH                   set nginx.lock pathname

  --user=USER                        set non-privileged user for
                                     worker processes
  --group=GROUP                      set non-privileged group for
                                     worker processes
... output trimmed ...                  

Compile-Time Options

In this section you will see the different compilation options available with ./configure script and their uses. This section offers a brief description of various options; the more detailed and compressive explanation with examples can be found in subsequent chapters.

Nginx Users and Groups

Using these parameters, you will ensure Nginx worker process executes under a particular user. It is necessary to create a non-privileged user with a strong password. This configuration parameter can be changed by editing the nginx.conf file. Table 2-2 shows you more information about the user and group parameters.

Table 2-2.
Illustrates the Nginx user and group parameter of nginx.conf

Command Parameter



Used to specify non-privileged user for Nginx worker processes.

Default is empty and Package Manager-based installation will create a user named nginx or www.


Used to specify non-privileged group for Nginx worker processes.

Default is empty and Package Manager-based installation will create a group named nginx or www.

Syntax example:

./configure --user=nginx --group=nginx

Nginx Configuration Paths Options

These configure command option contains all the various Nginx configuration paths details. You can always change any of these paths by editing the nginx.conf file. Various parameters are shown in Table 2-3.

Table 2-3. Illustrates the Nginx configuration paths

Command Parameter



Nginx server path, all files except configuration and libraries.

Default path is /usr/local/nginx and Package Manager-based installation uses the /etc/nginx directory.


Nginx executable path, this path hosts the nginx executable file.

Default path is /usr/local/nginx/sbin/nginx and Package Manager-based installation uses the /usr/sbin/nginx directory.


Nginx configurations path, this path will host the nginx.conf, mime.type and various other configuration files.

By default, the file is located at /usr/local/nginx/conf/ and the Package Manager installation hosts the file at /etc/nginx/.


Nginx process file, this file will store the process ID of the Nginx process.

By default, the file is located at /usr/local/nginx/logs/ and the Package Manager uses the path /var/run/.


Nginx lock file nginx.lock file, this file contains the lock information of the resources already in use by a particular process.

By default, the file is located at /usr/local/nginx/logs and the Package Manager uses the path /var/run/.

Syntax example:

./configure --prefix=/etc/nginx                                                                                                                                                  

Nginx Log Path Options

These parameters are used to configure log files locations for error files, HTTP access file, temporary paths for FastCGI, and other applications. Table 2-4 shows you the parameters that can be tweaked to change the path for various log files.

Table 2-4. Illustrates the log file locations for Nginx log files and applications

Command Parameter



Nginx server error log path, this file will contain the filename that will contain errors, warnings, and diagnostic error output.


Nginx server access log path, this file will contain the HTTP request log details of Nginx hosted web site.

By default, the HTTP access and error log file directory is /usr/local/nginx/logs/ and the Package Manager installs log files at /var/log/nginx/.


Temporary file location for HTTP requests. It holds the client request bodies.


Temporary file location for HTTP FastCGI, uWSGI, SCGI applications. This location stores temporary files with data received from FastCGI, uWSGI, and SCGI servers.

By default, the temporary path folders are created under the /usr/local/nginx/logs/ and the Package Manager configures /var/cache/nginx/ directory.



Syntax example:

./configure --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log                                                                                                                                                  

Enabling Nginx Modules

Table 2-5 shows a list of all the http modules that can be enabled when installing Nginx. These modules are not enabled by default when configuring Nginx from source. These http modules can be enabled using –with-http<module-name> options. It is highly recommended to install these modules during a compile-time option. You should enable the module that you would be using and as per the role of your Nginx server. If you need to enable a particular module after Nginx is configured the only option left is to recompile Nginx. Though Nginx update and upgrade has zero impact on your website, it is recommended to take extra precautions when recompiling from source.

Table 2-5. Illustrates different modules that can be enabled for Nginx

Command Parameter



This module provides support for HTTPS websites; this module requires OpenSSL to be enabled.


This module is used to get the real IP address of the client that is specified in the HTTP header.


This module is a filter module that is used to add text before and after a response.


This module is a substitution filter, and it is used to replace one specified string by another.


This module is used to enable WebDAV feature for file management using PUT, DELETE, MKCOL, COPY, and MOVE methods.


This module enables pseudo-streaming functionality for flash video file.


This module enables pseudo-streaming functionality for .mp4, .m4v, or .m4a files.


This module is used to decompress content for clients that do not a support gzip encoding method.


This module allows sending precompressed files with the .gz filename extension.


This module picks a random file in a directory to serve as an index file.


This module is used to authenticate the requested link using the hash to protect resource from unauthorized access.


This module provides access to basic status information.


This module implements client authorization based on response code.


This module provides support for Googles SPDY protocol. This is now a deprecated and is replaced by the newer HTTP/2 module.


This is a filter module that transforms XML responses using XSLT stylesheets.


This is a filter module that is used to process JPEG, GIF and PNG images.


This module is used for geo-targeting, it looks for client IP and compares it with the precompiled MaxMind database.


This module is used to serve a particular error message when the server faces a low memory issue.

Syntax example:

./configure --with-http_ssl_module --with-openssl=${BUILD_DIR}/openssl-1.0.1e --with-http_stub_status_module                                                                                                                                                  

Disabling Nginx Modules

Table 2-6 shows a list of some of the common modules that are enabled by default. You may choose to disable them when you have a server with a specific role. For example: if you want your server to be a dedicated web server, you don’t want a proxy or mail module on your server. These http modules that can be disabled using the –without-http<module-name> options.

Table 2-6. Illustrates different modules that can be disabled for Nginx

Command Parameter



Disables re-encoding Charset to another.


Disables gzip compression module.


Disable Server Side Include module.


Disables cookie-based client identification



Disables client IP address based access filtering.


Disables HTTP Basic Authentication module that is used to validate user access.


Disables directory listing of the website.


Disables geo-module allowing you to define variables with values depending on the client IP address.


Disables map module that is used to define map blocks.


Disables split testing module.


Disables blocking access to sites for requests with invalid “Referer” header.


Disables HTTP rewrite module.


Disables HTTP proxy module used to redirect to another server.


Disables FastCGI module.


Disables uWSGI module.


Disables SCGI module.


Disables memcached module that is used to obtain responses from memcached server.


Disables connection limit set as per the defined key rule.


Disables request processing limit set as per the defined key.


Disables transferring single pixel transparent gif.


Disables identifying User Agent from request header field.


Disables HTTP load balancing method for server group where the client-server mapping is based on the hashed key value.


Disables HTTP load balancing where requests are distributed across group of servers based on client IP address.


Disables HTTP load balancing where a request is passed to the server with the least number of active connections.


Disables cache for connections to upstream servers.


Disables POP3 module for mail server proxy.


Disables IMAP module for mail server proxy.


Disabled SMTP module for mail server proxy


Syntax example:

./configure --without-http_proxy_module --without-mail_pop3_module

Optimization Modules

This section discusses some of the optimization options that can be used during compilation such as using a specific C compiler or compiling Nginx for a specific CPU architecture. There, parameters are not required for default installation, but you can use them for optimizing your Nginx server build or to build Nginx for a particular CPU architecture. Table 2-7 lists the different optimization parameters available for Nginx.

Table 2-7. Illustrates different optimization parameters for Nginx

Command Parameter



Used to specify alternate location for C compiler.


Used to specify alternate location for C preprocessor.


Used to add parameters that will be added to the CFLAGS variable.


Used to define additional parameters that will be used during linking.


Used to specify different processor architecture.

Prerequisite Modules

This section covers some of the list of prerequisite modules that can be enabled or disabled on an as-needed basis. Table 2-8 lists the options available for the PCRE module.

Table 2-8. Illustrates different PCRE module options

Command Parameter



Disables PCRE libraries that are used for regular expression-based Nginx directive configuration and rewrite modules.


Force PCRE libraries usage.


Specifies path of the PCRE libraries, used when using specific version of PCRE libraries.


Used to specify additional build options for PCRE.


Used to build PCRE with JIT compilation support.

PCRE Options

MD5 Options

Table 2-9 lists the various options available to configure the MD5 module.

Table 2-9. Illustrates different MD5 module options

Command Parameter



Specifies the path to md5 library sources.


Used to specify additional build options for md5.


Uses md5 assembler sources.

SHA1 Options

Just like the MD5 module, SHA1 module can also be tweaked using various parameters as can be seen in Table 2-10.

Table 2-10. Illustrates different SHA1 module options

Command Parameter



Specifies the path to sha1 library sources.


Used to specify additional build options for sha1.


Uses sha1 assembler sources


zlib Options

To tweak compression-related aspects of the web server, use the parameters listed in Table 2-11 to configure the zlib module.

Table 2-11. Illustrates different zlib module options

Command Parameter



Specifies path of the zlib libraries, used when using specific version of zlib libraries.


Used to specify additional build options for zlib.


Uses zlib assembler sources that are optimized for Pentium or Pentiumpro CPU architecture.

OpenSSL Options

Table 2-12 highlights a couple of options used for OpenSSL.

Table 2-12. Illustrates different OpenSSL module options

Command Parameter



Specifies path of the OpenSSL libraries, used when using specific version of OpenSSL libraries.


Used to specify additional build options for OpenSSL.

Libatomic Options

Table 2-13 shows you the different parameters available for libatomic module.

Table 2-13. Illustrates different libatomic module options

Command Parameter



Forces libatomic libraries.


Specifies path of the libatomic libraries, used when using specific version of libatomic libraries


Other Options

There are yet another set of common parameters that can be used as can be seen in Table 2-14.

Table 2-14. Illustrates other options

Command Parameter



Disables HTTP server.


Disables HTTP cache.


Enables thread pool support.


Enables support for asynchronous disk IO operations.


Enables ipv6 support.


Sets the build name.


Sets the build location.


Used to add third-party modules during compiling Nginx. You will specify the path of the module in this parameter.


Enables debug logging.

Third-Party Modules

As you saw in chapter 1, one of the many features of Nginx is its modular nature. It has a very extensible architecture that enables support for plug-ins. The open source developer community has been very active and has been contributing in the development and enhancement of Nginx functionality.

  • You can find a list of all the third-party modules currently available at

  • You will need to patch Nginx in case of some third-party modules

  • You will need to configure Nginx using the ./configure command with the –add-module command. Like the example shown below (ensure that you have downloaded the module):

    # ./configure --add-module=../ngx_http_healthcheck_module
    # make
    # make install

Yes, it is that simple to enable any third-party module in Nginx


Compiling and Installing Nginx

Before you start configuring Nginx, you will need to implement some mechanism to identify if the installed version of Nginx on your server is indeed the compiled version. The first method is by using the
nginx –V command
from the terminal, but that will give you the configuration settings of your Nginx server. Imagine a scenario where you would have to compile and install Nginx on tens of servers and you need to know if all those servers have the compiled version of Nginx serving the request. An easy way to get this done is by having some sort of customization done in the source itself such that it can be accessed from a browser from external machines. For example, you can edit the default index.html page, which is available in the Nginx source folder under the path nginx-1.8.0/html.

After having looked at all the different configuration options, you are now armed to create your own binary as it fits your requirement. Since you are looking for installing a web server, your Nginx configuration would like something like the one below. You have complete freedom to add or remove any module you wish. The command discussed next is identical for both CentOS and Ubuntu.


Change the user to root using su on CentOS. In Ubuntu you will have to sudo every command.


There are a few prerequisites tasks that you need to do, before you can manually configure Nginx.

  • Create a group named ‘ nginx’:

    # groupadd –r nginx
  • Create a user name ‘ nginx’:

    # useradd –r nginx –g nginx

Manual Configuration

Here are the commands that you will have to run separately in the terminal window:

# ./configure --prefix=/etc/nginx \
 --user=nginx \
 --group=nginx \
 --sbin-path=/usr/sbin/nginx \
 --conf-path=/etc/nginx/nginx.conf \
 --pid-path=/var/run/ \
 --lock-path=/var/run/nginx.lock \
 --error-log-path=/var/log/nginx/error.log \
 --http-log-path=/var/log/nginx/access.log \
 --with-http_gzip_static_module \
 --with-http_stub_status_module \
 --with-http_ssl_module \
 --with-pcre \
 --with-file-aio \
 --with-http_realip_module \
 --without-http_scgi_module \
 --without-http_uwsgi_module \
 --without-http_proxy_module \                                                                                                                                                                                    

Below is the sample output of the above command. Here you can see that a Makefile was created in objs directory in the source folder. You can also see that configure was able to identify the PCRE, OpenSSL, and zlib libraries that we installed. You can also see that Nginx is showing you the exact location and log path directory as we mentioned.

... output trimmed ...                    
creating objs/Makefile

Configuration summary
  + using system PCRE library
  + using system OpenSSL library
  + md5: using OpenSSL library
  + sha1: using OpenSSL library
  + using system zlib library

  nginx path prefix: "/etc/nginx"
  nginx binary file: "/usr/sbin/nginx"
  nginx configuration prefix: "/etc/nginx"
  nginx configuration file: "/etc/nginx/nginx.conf"
  nginx pid file: "/var/run/"
  nginx error log file: "/var/log/nginx/error.log"
  nginx http access log file: "/var/log/nginx/access.log"
  nginx http client request body temporary files: "client_body_temp"
  nginx http fastcgi temporary files: "fastcgi_temp"

Now, you will need to execute the make command, which will compile all the code of the libraries to create a binary executable. Use the following command:

# make

Once the make command is executed successfully, the command ends with the following output:

... output trimmed ...                  
make[1]: Leaving directory `/home/nginx-1.8.0'
make -f objs/Makefile manpage
make[1]: Entering directory `/home/nginx-1.8.0'
sed -e "s|%%PREFIX%%|/etc/nginx|" \
        -e "s|%%PID_PATH%%|/var/run/|" \
        -e "s|%%CONF_PATH%%|/etc/nginx/nginx.conf|" \
        -e "s|%%ERROR_LOG_PATH%%|/var/log/nginx/error.log|" \
        < man/nginx.8 > objs/nginx.8

Now that the compilation is successful and the executable created, you can install Nginx using the command as shown


# sudo make install

The make install command executes the install part of the Makefile. The command essentially makes directories that do not exist and copies the configuration files and binaries to the specific folder. The output clearly shows the steps followed.

Scripted Configuration

Alternately, you can create a configuration script that you can use across multiple servers without having to worry about any human error while commanding input. Below is a sample script file that contains everything that you have used earlier with individual commands. Here the assumption is that you are creating the file under the source nginx directory that is under nginx-1.8.0.

# nano scripted

Add the script in the file:

export BUILD_DIR=/{path of the source directory}                
export NGINX_DIR=/etc/nginx
export SBIN_DIR=/usr/sbin
export PID_DIR=/var/run
export LOCK_DIR=/var/run
export LOG_DIR=/var/log/nginx
export RUN_DIR=/var/run
export CACHE_DIR=/var/cache

./configure \
                --prefix=${NGINX_DIR} \
                --sbin-path=${SBIN_DIR}/nginx \
        --conf-path=${NGINX_DIR}/nginx.conf \
                --pid-path=${PID_DIR}/ \
        --lock-path=${LOCK_DIR}/nginx.lock \
        --error-log-path=${LOG_DIR}/error.log \
        --http-log-path=${LOG_DIR}/access.log \
        --http-client-body-temp-path=${CACHE_DIR}/client_body_temp \
        --http-fastcgi-temp-path=${CACHE_DIR}/fastcgi_temp \
        --with-http_gzip_static_module \
        --with-http_stub_status_module \
        --with-http_ssl_module \
        --with-pcre \
        --with-file-aio \
        --with-http_realip_module \
        --without-http_scgi_module \
        --without-http_uwsgi_module \
        --without-http_proxy_module \
        --user=nginx \
        --group=nginx \                                                                                                                                                                                                      

Convert the script into an executable using the following command:

# chmod u+x scripted

Now, you can configure Nginx using a single command and then complete the installation with make and make install commands:

# ./scripted
# make
# make install

Nginx does not start automatically when you do source-based installation. You will have to start the Nginx by manually running the nginx process like the case above /usr/sbin/nginx in the terminal window.

Enable Nginx Service on Reboot

Installing Nginx from source does not create the init script that will autostart the Nginx process after server reboot. Instead of reinventing the wheel, you can use the script that’s available online. Visit
to access the script.

  • You can download the script directly on the server as /etc/init.d/nginx file:

    # sudo wget -O /etc/init.d/nginx
  • Once the script is downloaded you will need to make it as an executable:

    # sudo chmod +x /etc/init.d/nginx
  • You can now set the service to start automatically when the server reboots


  • On CentOS:

    # chkconfig --add nginx
    # chkconfig --level 345 nginx on

    On Ubuntu:

    # sudo update-rc.d nginx defaults
  • You can verify if you are able to start Nginx using a basic service <process> start command:

    # service nginx start

Troubleshooting Service Start

It happens that once you have followed the steps as mentioned, there is a possibility of facing an issue of not being able to start the service. You may come across an issue like the following:

# journalctl –xn
-- Logs begin at Sun 2015-09-27 20:16:54 IST, end at Sun 2015-09-27 21:00:50 IST. --
Sep 27 20:57:37 ncentos.local systemd[1]: Unit nginx.service entered failed state.
Sep 27 21:00:44 ncentos.local systemd[1]: Reloading.
Sep 27 21:00:44 ncentos.local systemd[1]: [/usr/lib/systemd/system/dm-event.socket:10] Unknown lvalue 'RemoveOnStop' in section 'So
Sep 27 21:00:44 ncentos.local systemd[1]: [/usr/lib/systemd/system/lvm2-lvmetad.socket:9] Unknown lvalue 'RemoveOnStop' in section
Sep 27 21:00:50 ncentos.local systemd[1]: Starting SYSV: Nginx is an HTTP(S) server, HTTP(S) reverse proxy and IMAP/POP3 proxy server
-- Subject: Unit nginx.service has begun with start-up
-- Defined-By: system
-- Support:
-- Unit nginx.service has begun starting up.
Sep 27 21:00:50 ncentos.local nginx[4971]: Starting nginx: nginx: [emerg] getpwnam("nginx") failed
Sep 27 21:00:50 ncentos.local nginx[4971]: [FAILED]
Sep 27 21:00:50 ncentos.local systemd[1]: nginx.service: control process exited, code=exited status=1
Sep 27 21:00:50 ncentos.local systemd[1]: Failed to start SYSV: Nginx is an HTTP(S) server, HTTP(S) reverse proxy and IMAP/POP3 pro
-- Subject: Unit nginx.service has failed
-- Defined-By: system
-- Support:
-- Unit nginx.service has failed.
-- The result is failed.
Sep 27 21:00:50 ncentos.local systemd[1]: Unit nginx.service entered failed state                                                                                                                      .

That error clearly shows that an Nginx user does not exist. You will need the Nginx user account to execute the Nginx process as that is what our configuration step contains. You can add the user using the command shown below to resolve the above error:

# groupadd –r nginx
# useradd -r nginx -g nginx
        |                 |
     User            Group

You now have a working version Nginx running on the server. The next and final step for this chapter is to verify whether the website is working.

Verifying Web Server Installation

The simplest way to verify if Nginx is working on the server is to check it locally. We already have lynx installed on the server, so we will use the same to verify the Nginx website.

# lynx http://localhost

Figure 2-1 shows that request has been served by the compiled version of Nginx.

Figure 2-1. Compiled version of Nginx seen using Lynx

You can check the Nginx process that is executing on the server using the following command:

# ps aux | grep nginx

The output is as follows:

root      5034  0.0  0.1  47156  1072 ?        Ss   21:05   0:00 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
nginx     5036  0.0  0.2  47612  2088 ?        S    21:05   0:00 nginx: worker process
root      5075  0.0  0.0 112612   740 pts/0    S+   21:26   0:00 grep --color=auto nginx

Firewall Configuration

You will need to open port 80 on the server such that you can access the website from outside of the local server. You will need to configure the firewall

for the same, as CentOS has port 80 blocked by default on the server.

On CentOS

The command to add port 80 in the firewall rules, you will need to execute the command below:

# firewall-cmd --permanent --add-port=80/tcp
# firewall-cmd --reload

On Ubuntu

To open port 80 on Ubuntu, the command is iptables.

# sudo iptables –A INPUT –p tcp --dport 80 –j ACCEPT

You can verify the port by checking the firewall rules, which is done by using this command:

# sudo iptables –L

Now the website is accessible from outside of the CentOS server.

Nginx in Amazon Elastic Compute Cloud (EC2)

Nginx is equally easy to set up in the cloud. In this section you will learn about how easily you can get up and running with your own web server using Amazon Web Services (AWS) EC2 instance
. The first step in the sign-up in this direction is to sign up for an account at
. The sign-up is free of cost, but be mindful of the fact that you get only limited hours for free. Hence, you need to read the terms and conditions carefully. At the time of writing, you can host one t2.micro server
free for one year using your credit card.

Creating an Amazon EC2 instance with Nginx installed is fairly simple and straightforward:

  • Sign in using your user name at

  • In the Compute section, click EC2.

  • Click the Launch Instance button and you will be redirected to a UI with a wizard. You can use any Linux version. Choosing a 64-bit server is generally a better idea since it can address a wider memory address space. Figure 2-2 shows how the launch wizard looks like at the time of writing this book. For the purpose of this book, the first instance (Amazon Linux AMI) will be used


    Figure 2-2.
    Amazon AWS EC2 Wizard
    – Step 1
  • In step 2 of the wizard (see Figure 2-3), select t2.micro and click the Next:Configure Instance Details button.

    Figure 2-3.
    Amazon AWS EC2 Wizard
    – Step 2
  • You can leave the defaults in steps 3 through 5 of the wizard

    . There are plenty of options to choose from, a discussion of which is beyond the scope of this book. However, they are quite simple to understand, and I urge you to read the documentation while you follow along with the steps.

  • Step 6 is very crucial, since this is where you make your web server public. Click Add Rule and make the changes so that it looks similar to Figure 2-4. Basically, you will be adding one more rule to the firewall and allowing this server to be accessible on port 80 from anywhere.

    Figure 2-4.
    Amazon AWS EC2 Wizard
    – Step 6
  • Once the server is launched, you need to click EC2 Dashboard ➤ Running Instances ➤ Your Server

  • You can now click on the connect button and the pop-up will tell you how to connect to your server using SSH. For the demo server we set up, it asked to use the following command:

    ssh -i "mykey.pem"
  • Once logged on the server, the steps were exactly how it has been explained earlier in this chapter. It took just two commands to get Nginx up and running. Point your browser to the IP address and you will find your web server running smoothly.

sudo yum install nginx
sudu service nginx start


In this chapter, you learned about various ways of installing Nginx in different Linux distros. You should now be comfortable with making a decision regarding installation using pre-built packages or building your own set of binaries. Both of these methods are useful in different scenarios, and it is important that you are comfortable with either option. While picking an option you should be mindful about the maintenance aspects of Nginx as well. You have also learned about some troubleshooting basics and automating tasks such as restarting Nginx whenever the server is rebooted. In the upcoming chapters, you will learn that Nginx can be reconfigured just as easily.

Comments are closed.