in

How to Install Nginx on Ubuntu or CentOS/RHEL – An In-Depth Guide

Nginx has become one of the most popular open source web servers over the past decade. As a data analyst and technology geek, I wanted to share an in-depth guide on the various methods for installing Nginx. Whether you‘re looking to set up a simple web server or optimize performance for large scale web apps, this guide will help you get Nginx running smoothly.

Why Use Nginx?

Before we dig into the installation, let‘s go over some key reasons why you may want to use Nginx in the first place:

  • High performance – Nginx can reliably handle 10,000+ concurrent connections with very low memory usage. This makes it well suited for handling large traffic loads.

  • Web serving – It can serve static files, load balance traffic to upstream servers, and act as a reverse proxy.

  • Efficiency – Nginx has a very lightweight and modular architecture. The event-driven model consumes fewer resources than legacy servers like Apache.

  • Flexibility – There are over 900+ community modules available to extend Nginx‘s functionality for specialized use cases.

  • Reliability – Companies like Netflix, Hulu, Cloudflare, and Airbnb rely on Nginx to serve massive amounts of web traffic.

Nginx powers over 30% of the world‘s busiest sites according to W3Tech‘s survey data. The performance gains compared to other options have made it very appealing for modern web applications.

Nginx Usage Stats

Now let‘s get into the details of how to install it on Linux!

Installation on Ubuntu with Apt

The easiest way to install Nginx on Ubuntu is by using the apt package manager. Here‘s how we‘ll install it:

First, log into your Ubuntu server as root or with sudo privileges:

sudo su -

Next, update your package lists to ensure you have the latest package versions:

apt-get update

Now install Nginx along with the required dependencies:

apt-get install nginx

This will install Nginx and related packages necessary to run it:

Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following additional packages will be installed:
  fontconfig-config fonts-dejavu-core libfontconfig1 libgd3 libjbig0 libjpeg-turbo8 libjpeg8
  libnginx-mod-http-geoip libnginx-mod-http-image-filter libnginx-mod-http-xslt-filter
  libnginx-mod-mail libnginx-mod-stream libtiff5 libwebp6 libxpm4 nginx-common nginx-core
Suggested packages:
  libgd-tools fcgiwrap nginx-doc ssl-cert
The following NEW packages will be installed:
  fontconfig-config fonts-dejavu-core libfontconfig1 libgd3 libjbig0 libjpeg-turbo8 libjpeg8
  libnginx-mod-http-geoip libnginx-mod-http-image-filter libnginx-mod-http-xslt-filter
  libnginx-mod-mail libnginx-mod-stream libtiff5 libwebp6 libxpm4 nginx nginx-common
  nginx-core
0 upgraded, 20 newly installed, 0 to remove and 0 not upgraded.
Need to get 2,462 kB of archives.
After this operation, 9,217 kB of additional disk space will be used.

As you can see, this installs the core Nginx binaries along with many useful modules like GeoIP, image processing, XSLT filtering, and mail capabilities.

Once the installation completes, verify the version to ensure it installed properly:

nginx -v

This will print out the version number:

nginx version: nginx/1.18.0 (Ubuntu)

That‘s it! Nginx is now installed on your Ubuntu system and ready to be configured. The apt approach makes it quick and painless to get up and running.

Installation on CentOS/RHEL with Yum

If you‘re using CentOS or RHEL, the yum package manager makes installing Nginx a breeze.

Log into your CentOS/RHEL server as root:

sudo su -

You‘ll need to install the EPEL repository first, which contains the Nginx package:

yum install epel-release

Now install Nginx:

yum install nginx

This will install Nginx and handle any required dependencies:

Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
 * base: mirror.net.cen.ct.gov
 * epel: mirror.es.its.nyu.edu
 * extras: linux.mirrors.es.net
 * updates: mirrors.gigenet.com
Resolving Dependencies
--> Running transaction check
---> Package nginx.x86_64 1:1.14.1-9.el7 will be installed  
--> Processing Dependency: nginx-filesystem = 1:1.14.1-9.el7 for package: 1:nginx-1.14.1-9.el7.x86_64
--> Processing Dependency: libxslt.so.1(LIBXML2_1.0.18)(64bit) for package: 1:nginx-1.14.1-9.el7.x86_64
--> Running transaction check
---> Package libxslt.x86_64 0:1.1.28-6.el7 will be installed
---> Package nginx-filesystem.noarch 1:1.14.1-9.el7 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

================================================================================================================
 Package                 Arch           Version                       Repository                            Size
================================================================================================================
Installing:
 nginx                   x86_64         1:1.14.1-9.el7                epel                                516 k
Installing for dependencies:
 libxslt                 x86_64         1.1.28-6.el7                  base                               242 k
 nginx-filesystem        noarch         1:1.14.1-9.el7                epel                                 19 k

Transaction Summary
================================================================================================================
Install  3 Packages

Total download size: 778 k
Installed size: 3.0 M
Is this ok [y/d/N]: y

This handles all of the dependency resolution and downloads the Nginx packages.

Double check the installed version:

nginx -v

You should see output like:

nginx version: nginx/1.14.1

Nginx is installed and ready for configuration on CentOS/RHEL as well!

Installing Nginx from Source Code

While using apt or yum is the easiest approach, you may want to compile Nginx directly from source in some cases:

  • You need a specific Nginx version or custom build configuration
  • You want to optimize the build parameters and options
  • You need to install Nginx on servers without internet access

Here‘s an overview of compiling Nginx from source code on CentOS/RHEL:

First, install the development tools, OpenSSL, and PCRE dependencies:

yum groupinstall "Development Tools" 
yum install openssl-devel pcre-devel

Next, download the latest stable source tarball from nginx.org:

wget http://nginx.org/download/nginx-1.18.0.tar.gz

Extract the source archive:

tar -zxvf nginx-1.18.0.tar.gz

Change to the extracted source directory:

cd nginx-1.18.0

Now configure the build parameters and options as desired. Here we‘ll install it under /opt/nginx with SSL module enabled:

./configure --prefix=/opt/nginx --with-http_ssl_module

Compile the Nginx source code:

make

And install the compiled binaries and modules to the configured prefix:

make install

This compiles Nginx with the specified options and installs it to /opt/nginx.

Check the version to verify a successful source install:

/opt/nginx/sbin/nginx -v

You should see output like:

nginx version: nginx/1.18.0

The source installation approach allows much more customization and control over the Nginx build process. You can fine tune the parameters to optimize Nginx‘s performance for your specific environment.

Starting and Stopping Nginx

The method for starting and stopping Nginx depends on how you installed it.

For repository installs, use the systemd unit:

systemctl start nginx
systemctl stop nginx

For source installs, use the nginx executable directly:

/opt/nginx/sbin/nginx
/opt/nginx/sbin/nginx -s stop

You can also restart Nginx after config changes:

systemctl restart nginx
/opt/nginx/sbin/nginx -s reload 

Check the logs if you run into issues:

tail -F /var/log/nginx/error.log

This will help you troubleshoot any problems with starting Nginx or loading the configuration.

Securing and Hardening Nginx

Since Nginx is exposed to the public internet, it‘s important to follow security best practices:

  • Run Nginx as a non-root user for enhanced security
  • Limit connections to Nginx to authorized sources
  • Disable any unnecessary modules to reduce your attack surface
  • Generate SSL/TLS certificates to encrypt connections
  • Restrict file permissions on web roots, logs, and configs
  • Keep Nginx fully patched and updated
  • Configure logging and monitoring such as health checks
  • Enable a WAF or use tools like ModSecurity to protect against attacks

Additionally, you should learn how to properly configure the Nginx access controls, SSL settings, connection handling parameters, and other options to harden your environment.

There are many in-depth Nginx hardening guides available for production environments. Be sure to follow the latest recommended techniques to prevent security issues.

Closing Thoughts

I hope this guide gives you a comprehensive overview of the most common ways to install Nginx, along with some best practices to securely run it. The package manager approach with apt/yum is great for simplicity. And compiling from source allows maximum control and optimization.

Here are some key takeaways:

  • Use apt for easy installs on Ubuntu
  • Yum with EPEL repo handles installs for CentOS/RHEL
  • Compiling from source offers more customization and tuning
  • Follow security best practices for production deployments

Nginx is a powerful web server with an array of advanced features. Once you have it installed and hardened, you can start leveraging Nginx for your web applications and services. Let me know if you have any other questions!

AlexisKestler

Written by Alexis Kestler

A female web designer and programmer - Now is a 36-year IT professional with over 15 years of experience living in NorCal. I enjoy keeping my feet wet in the world of technology through reading, working, and researching topics that pique my interest.