How to Install Nginx on Ubuntu 18.04
7 min read

How to Install Nginx on Ubuntu 18.04

In this tutorial, you will learn to install Nginx on Ubuntu 18.04. Nginx is one of the most renowned web servers in the world which can be credited for hosting the largest and busiest websites.
How to Install Nginx on Ubuntu 18.04

Introduction

Before we begin talking about how to install Nginx on Ubuntu 18.04, let’s briefly understand – What is Nginx?

Nginx is one of the most renowned web servers in the world which can be credited for hosting the largest and busiest websites. It is preferred over Apache due to its resource friendliness and can be used as a reverse proxy and a web server.

In this tutorial, you’ll install Nginx on Ubuntu 18.04 server with a step-by-step approach.

Prerequisites

Make sure you are logged in as a user with sudo privilege and there is no other web server running on port 80 or 443.

Step 1 -  Install Nginx

Nginx can be installed from the default repositories of Ubuntu with the help of the apt packaging system.

1) Firstly, you need to update the package list and install Nginx using the following commands:

sudo apt update
sudo apt install nginx

2) On successful installation, Nginx will start automatically. Check the status of the service using the following command:

sudo systemctl status nginx

Step 2 - Firewall Settings

The firewall software needs to be adjusted so that it can allow access to the service. Do it before testing the Nginx.

1) You need to list the application configuration that ufw knows by typing the below command:

sudo ufw app list

You will get the listing of the application profiles:

Output

Available applications:
  Nginx Full
  Nginx HTTP
  Nginx HTTPS
  OpenSSH

There are three profile options available to choose from in Nginx

  • Nginx Full: It opens both port 80 (normal, unencrypted web traffic) and port 443 (TLS/SSL encrypted traffic).
  • Nginx HTTP: Opens only port 80 (normal, unencrypted web traffic).
  • Nginx HTTPS: Only opens port 443 (TLS/SSL encrypted traffic).

Enable the most restrictive profile that only allows the traffic you've configured. In this tutorial we haven't configured SSL hence we only need to allow traffic on port 80.

2) This can be enabled by typing the following command:

sudo ufw allow 'Nginx HTTP'

3) Check the status with the below command:

sudo ufw status

4) The HTTP output will be similar to the below output:

Output

Status: active

To                         Action      From
--                         ------      ----
OpenSSH                    ALLOW       Anywhere                  
Nginx HTTP                 ALLOW       Anywhere                  
OpenSSH (v6)               ALLOW       Anywhere (v6)             
Nginx HTTP (v6)            ALLOW       Anywhere (v6)

Step 3 - Checking the Web Server

On completing the installation, Ubuntu 18.04 runs Nginx automatically. The web server should be up and running.

1) To check the systemd init and make sure the service is running, type the following command:

systemctl status nginx
Output

● nginx.service - A high performance web server and a reverse proxy server
   Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
   Active: active (running) since Fri 2018-04-20 16:08:19 UTC; 3 days ago
     Docs: man:nginx(8)
 Main PID: 2369 (nginx)
    Tasks: 2 (limit: 1153)
   CGroup: /system.slice/nginx.service
           ├─2369 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
           └─2380 nginx: worker process

The above output proves that the service is running fine. Though the best way to test the same is to request a page from Nginx itself.

You can test the working of the service by accessing the Nginx's default landing page and navigating to your system's IP address. One can easily find the IP address through different ways and means.

2) You can type the following command in your server's command prompt:

ip addr show eth0 | grep inet | awk '{ print $2; }' | sed 's/\/.*$//'

You will receive few lines as output. Try each of them on your web browser to check if they work.

3) The following command can help you obtain your public IP address, as seen from a different location on the internet:

curl -4 icanhazip.com

4) Enter the IP address in your browser's address bar.

http://your_server_ip

The following page, which is the default Nginx landing page should be visible.

Nginx has this page included to show that the server is running fine.

Step 4 - Managing Nginx Processes

Once the webserver is operational, let's explore some basic management commands.

For stopping the web server, use:

sudo systemctl stop nginx

To restart the webserver, use:

sudo systemctl start nginx

For stopping and restarting the service, use:

sudo systemctl restart nginx

Nginx has a feature wherein it reloads without dropping connections. This is useful when you are just making changes to the configuration. To do this, use:

sudo systemctl reload nginx

Nginx is designed to start automatically while the server boots, to stop this use the following command:  

sudo systemctl disable nginx

If you want to re-enable the above feature, use:

sudo systemctl enable nginx

Step 5 - Setting Up the Server Blocks

Server blocks are similar to Apache Virtual hosts which can be helpful in hosting more than one domain from a single server. For this tutorial, we will be using example.com you must replace this with your domain name.

By default Nginx has one server block enabled to server the documents from /var/www/html. It works perfectly fine for hosting a single site but if you want to host multiple sites then, create a new directory within /var/www for your example.com site.

1) Create the directory for example.com, with the help of -p flag for creating necessary parent directories. The following command can be used:

sudo mkdir -p /var/www/example.com/html

2) Now, you have to assign ownership of the directory with $USER environment variable:

sudo chown -R $USER:$USER /var/www/example.com/html

3) Permissions of the web roots should be correct since the umask value is untouched. You can still check the same with the following command:

sudo chmod -R 755 /var/www/example.com

4) You now have to create index.html, a sample page using nano or any other editor:

nano /var/www/example.com/html/index.html

5) Next, add the following HTML sample:

<html>
    <head>
        <title>Welcome to Example.com!</title>
    </head>
    <body>
        <h1>Success!  The example.com server block is working!</h1>
    </body>
</html>

6) Save the file and close it when done.

7) For Nginx to serve the content, a server block with the correct directives needs to be created. We'll be creating a new configuration instead of modifying the default one at /etc/nginx/sites-available/example.com:

sudo nano /etc/nginx/sites-available/example.com

8) Now, paste the following configuration, similar to the default but updated for the new domain and directory name.

server {
        listen 80;
        listen [::]:80;

        root /var/www/example.com/html;
        index index.html index.htm index.nginx-debian.html;

        server_name example.com www.example.com;

        location / {
                try_files $uri $uri/ =404;
        }
}

9) The root configuration has been updated to our directory and the server_name to our domain name.

7) After that, enable the file by creating a link from it to the sites-enabled directory, from which Nginx reads while starting up.

sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/

Now, two server blocks have been enabled to respond to requests based on listen and server_name directories.

  • example.com: Responds to requests for example.com and www.example.com.
  • default: Responds to any requests on port 80 that does not match the other two blocks.

8) It is extremely important to adjust a single value in the /etc/nginx/nginx.conf file to avoid a possible hash bucket memory problem. The following file needs to be opened:

sudo nano /etc/nginx/nginx.conf

9) You then have to find the server_names_hash_bucket_size and remove the # symbol to uncomment the following:

...
http {
    ...
    server_names_hash_bucket_size 64;
    ...
}
...

10) Save the file and then close it.

11) Now, you have to run a test to check for any syntax errors in any of the Nginx files:

sudo nginx -t

12) If no issues are detected, restart Nginx to enable changes

sudo nginx -t

You can now visit http://example.comand see the following. This signifies that Nginx is serving your domain.

Step 6 - Get Familiar with Important Nginx Files and Directories

Now let's check out some important files and directories of Nginx. It will get simpler to manage the Nginx service if you are aware of these things/

Content

  • /var/www/html: The actual web content only consists of the default Nginx page which is served out of the /var/www/html directory. This can be changed by altering Nginx configuration files.

Server Configuration

  • /etc/nginx: The Nginx configuration directory. All of the Nginx configuration files can be found here.
  • /etc/nginx/nginx.conf: The main Nginx configuration file which can be modified to make changes to the Nginx global configuration.
  • /etc/nginx/sites-available/: Per-site server blocks can be stored in this directory. Configuration files found in this directory will not be used unless they are linked to the sites-enabled directory. All server block configurations are done in this directory and then enabled by linking to the other directory.
  • /etc/nginx/sites-enabled/: This directory has enabled per-site server blocks stored. These are created by linking to configuration files found in the sites-available directory.
  • /etc/nginx/snippets: Configuration fragments that can be included elsewhere in the Nginx configuration are present in this directory. Potentially repeatable configuration segments are great for refactoring into snippets.

Server Logs

  • /var/log/nginx/access.log: Every request is recorded in this log file unless configured to do otherwise.
  • /var/log/nginx/error.log: All Nginx errors are recorded in this log.

Conclusion

We hope this detailed guide helped you understand how to install Nginx on Ubuntu 18.04 server. To learn more about Nginx installation on Ubuntu 18.04 server, check out the official Nginx server website.

If you have any queries, please leave a comment below and we’ll be happy to respond to them for sure.