Tutorial

How To Install Nginx on Ubuntu 18.04

Updated on October 19, 2021
English
How To Install Nginx on Ubuntu 18.04
Not using Ubuntu 18.04?Choose a different version or distribution.
Ubuntu 18.04

Introduction

Nginx is one of the most popular web servers in the world and is responsible for hosting some of the largest and highest-traffic sites on the internet. It is more resource-friendly than Apache in most cases and can be used as a web server or reverse proxy.

In this guide, you’ll learn how to install Nginx on your Ubuntu 18.04 server and about important Nginx files and directories.

Prerequisites

Before you begin this guide, you should have a regular, non-root user with sudo privileges and a basic firewall configured on your server. You can learn how to configure a regular user account by following our initial server setup guide for Ubuntu 18.04.

When you have an account available, log in as your non-root user to begin.

Step 1 – Installing Nginx

Since Nginx is available in Ubuntu’s default repositories, it is possible to install it from these repositories using the apt packaging system.

Since this may be your first interaction with the apt packaging system in this session, update the local package index so that you have access to the most recent package listings. Afterward, you can install nginx:

  1. sudo apt update
  2. sudo apt install nginx

After accepting the procedure, apt will install Nginx and any required dependencies to your server.

Step 2 – Adjusting the Firewall

Before testing Nginx, the firewall software needs to be adjusted to allow access to the service. Nginx registers itself as a service with ufw upon installation, making it straightforward to allow Nginx access.

List the application configurations that ufw knows how to work with by typing the following:

  1. sudo ufw app list

Your output should be a list of the application profiles:

Output
Available applications: Nginx Full Nginx HTTP Nginx HTTPS OpenSSH

This list displays three profiles available for Nginx:

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

It is recommended that you enable the most restrictive profile that will still allow the traffic you’ve configured. Since you haven’t configured SSL for your server yet in this guide, you’ll only need to allow traffic on port 80.

You can enable this by typing the following:

  1. sudo ufw allow 'Nginx HTTP'

Then, verify the change:

  1. sudo ufw status

You should receive a list of HTTP traffic allowed in the 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)

Now that you’ve added the appropriate firewall rule, you can check that your web server is running and able to serve content correctly.

Step 3 – Checking your Web Server

At the end of the installation process, Ubuntu 18.04 starts Nginx. The web server should already be up and running.

Check with the systemd init system to make sure the service is running:

  1. 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: en Active: active (running) since Fri 2021-10-01 21:36:15 UTC; 35s ago Docs: man:nginx(8) Main PID: 9039 (nginx) Tasks: 2 (limit: 1151) CGroup: /system.slice/nginx.service ├─9039 nginx: master process /usr/sbin/nginx -g daemon on; master_pro └─9041 nginx: worker process

This output shows that the service has started successfully. However, the best way to test this is to actually request a page from Nginx.

You can access the default Nginx landing page to confirm that the software is running properly by navigating to your server’s IP address. If you do not know your server’s IP address, you can get it a few different ways.

Try typing the following at your server’s command prompt:

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

You will receive a few lines. You can try each in your web browser to confirm if they work.

An alternative is running the following command, which should generate your public IP address as identified from another location on the internet:

  1. curl -4 icanhazip.com

When you have your server’s IP address, enter it into your browser’s address bar:

http://your_server_ip

You should receive the default Nginx landing page:

Nginx default page

This page is included with Nginx to verify that the server is running correctly.

Step 4 – Managing the Nginx Process

Now that you have your web server up and running, let’s review some basic management commands.

To stop your web server, type the following:

  1. sudo systemctl stop nginx

To start the web server when it is stopped, type the following:

  1. sudo systemctl start nginx

To stop and then start the service again, type the following:

  1. sudo systemctl restart nginx

If you are simply making configuration changes, you can often reload Nginx without dropping connections instead of restarting it. To do this, type the following:

  1. sudo systemctl reload nginx

By default, Nginx is configured to start automatically when the server boots. If this is not what you want, you can disable this behavior by typing the following:

  1. sudo systemctl disable nginx

To re-enable the service to start up at boot, you can type the following:

  1. sudo systemctl enable nginx

Nginx should now start automatically when the server boots again.

When using the Nginx web server, server blocks (similar to virtual hosts in Apache) can be used to encapsulate configuration details and host more than one domain from a single server. We will set up a domain called your_domain, but you should replace this with your own domain name. To learn more about setting up a domain name with DigitalOcean, see our Introduction to DigitalOcean DNS.

Nginx on Ubuntu 18.04 has one server block enabled by default that is configured to serve documents out of a directory at /var/www/html. While this works well for a single site, it can become unwieldy if you are hosting multiple sites. Instead of modifying /var/www/html, let’s create a directory structure within /var/www for our your_domain site, leaving /var/www/html in place as the default directory to be served if a client request doesn’t match any other sites.

Create the directory for your_domain as follows, using the -p flag to create any necessary parent directories:

  1. sudo mkdir -p /var/www/your_domain/html

Next, assign ownership of the directory with the $USER environment variable:

  1. sudo chown -R $USER:$USER /var/www/your_domain/html

The permissions of your web roots should be correct if you haven’t modified your umask value, but you can make sure by typing the following:

  1. sudo chmod -R 755 /var/www/your_domain

Next, create a sample index.html page using nano or your favorite editor:

  1. nano /var/www/your_domain/html/index.html

Inside, add the following sample HTML:

/var/www/your_domain/html/index.html
<html>
    <head>
        <title>Welcome to your_domain!</title>
    </head>
    <body>
        <h1>Success! The your_domain server block is working!</h1>
    </body>
</html>

Save and close the file when you are finished. If you used nano, you can exit by pressing CTRL + X then Y and ENTER.

In order for Nginx to serve this content, it’s necessary to create a server block with the correct directives. Instead of modifying the default configuration file directly, make a new one at /etc/nginx/sites-available/your_domain:

  1. sudo nano /etc/nginx/sites-available/your_domain

Add the following configuration block, which is similar to the default, but updated for your new directory and domain name:

/etc/nginx/sites-available/your_domain
server {
        listen 80;
        listen [::]:80;

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

        server_name your_domain.com www.your_domain;

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

Notice that we’ve updated the root configuration to the new directory, and the server_name to the domain name. Save and close the file when you are finished.

Next, enable the file by creating a link from it to the sites-enabled directory, which Nginx reads from during startup:

  1. sudo ln -s /etc/nginx/sites-available/your_domain /etc/nginx/sites-enabled/

Two server blocks are now enabled and configured to respond to requests based on their listen and server_name directives (you can read more about how Nginx processes these directives here):

  • your_domain: Will respond to requests for your_domain and www.your_domain.
  • default: Will respond to any requests on port 80 that do not match the other two blocks.

To avoid a possible hash bucket memory problem that can arise from adding additional server names, it is necessary to adjust a single value in the /etc/nginx/nginx.conf file. Open the file:

  1. sudo nano /etc/nginx/nginx.conf

Find the server_names_hash_bucket_size directive and remove the # symbol to uncomment the line:

/etc/nginx/nginx.conf
...
http {
    ...
    server_names_hash_bucket_size 64;
    ...
}
...

Save and close the file when you are finished.

Next, test to make sure that there are no syntax errors in any of your Nginx files:

  1. sudo nginx -t

If there aren’t any problems, restart Nginx to enable your changes:

  1. sudo systemctl restart nginx

Nginx should now be serving your domain name. You can test this by navigating to http://your_domain, where you should see something like the following:

Nginx first server block

Step 6 – Getting Familiar with Important Nginx Files and Directories

Now that you know how to manage the Nginx service itself, you should take a few minutes to familiarize yourself with a few important directories and files.

Content

  • /var/www/html: The actual web content, which by default only consists of the default Nginx page you saw earlier, 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 reside here.
  • /etc/nginx/nginx.conf: The main Nginx configuration file. This can be modified to make changes to the Nginx global configuration.
  • /etc/nginx/sites-available/: The directory where per-site server blocks can be stored. Nginx will not use the configuration files found in this directory unless they are linked to the sites-enabled directory. Typically, all server block configuration is done in this directory, and then enabled by linking to the other directory.
  • /etc/nginx/sites-enabled/: The directory where enabled per-site server blocks are stored. Typically, these are created by linking to configuration files found in the sites-available directory.
  • /etc/nginx/snippets: This directory contains configuration fragments that can be included elsewhere in the Nginx configuration. Potentially repeatable configuration segments are good candidates for refactoring into snippets.

Server Logs

  • /var/log/nginx/access.log: Every request to your web server is recorded in this log file unless Nginx is configured to do otherwise.
  • /var/log/nginx/error.log: Any Nginx errors will be recorded in this log.

Conclusion

Now that you have your web server installed, you have many options for the type of content to serve and the technologies you want to use to create a richer experience.

If you’d like to build out a more complete application stack, check out this article on how to configure a LEMP stack on Ubuntu 18.04.

Want to easily configure a performant, secure, and stable Nginx server? Try our free open-source Nginx tool.

Learn more here

About the authors


Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
10 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Will I be able to access Radio Romania International? Their address is www.rri.ro

This works flawlessly. Very clear guide. Thankyou!

After step 2, I got Status: inactive and discovered that I needed to run sudo ufw enable. And after that the output was a bit different than described:

Status: active

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

I was also getting Status: inactive by typing sudo ufw allow 'Nginx HTTP'. But I solved it by using sudo ufw enable command.

Hi,

On vmware I have Ubuntu 18.04. When I try this “ip addr show eth0 | grep inet | awk ‘{ print $2; }’ | sed ‘s//.*$//’” I got error saying “Device “eth0” does not exist.” My DNS is working. I also follow the tutorial and create block for domin. But I cannot make it work. when I type http://127.0.0.1/ I can see default nginx index.html But when I try to write my domain it looks like its keep searching. Any idea?

niyazi@niyazi-virtual-machine:~$ sudo lshw -short | grep network /0/100/15/0 ens160 network VMXNET3 Ethernet Controller /2 docker0 network Ethernet interface

Very good guidelines.

I follow the tutorial and set up my Nginx as well as I configure to use as a bypass proxy. When I try to type as http://myserverip/ I get 502 bad gateway error. I am using Nginx bypass proxy so I can test my web api. I created single customize html and put in root /var/www/html/data/; but I still keep getting 502 bad gateway error. How can I correct my configuration?

Below is my Nginx configuration. Any help please?

server {
            charset UTF-8;
    	    listen 80;
            listen [::]:80;
            error_log    /var/log/nginx/niyazi.com.error.log debug;
            rewrite_log on;
            server_name mod.niyazi.com;
            include snippets/letsencrypt.conf;
            root /var/www/html/data/;
            return 301 https://mod.niyazi.com$request_uri;
    }
    
    server {
            charset UTF-8;
        	listen 443 ssl http2;
        	server_name mod.niyazi.com;
        	ssl_certificate /etc/letsencrypt/live/mod.niyazi.com/fullchain.pem;
        	ssl_certificate_key /etc/letsencrypt/live/mod.niyazi.com/privkey.pem;
        	ssl_trusted_certificate /etc/letsencrypt/live/mod.niyazi.com/chain.pem;
        	include snippets/ssl.conf;
        	include snippets/letsencrypt.conf;
            location / {
                    proxy_pass http://192.168.12.120:8280/;
            }
           	if ($request_method !~ ^(GET|HEAD|POST)$ )
    	{
    		return 405;
    	}   
    }

http://example.com from where? The client? How would client know what this is referring too? I get some other page describing Example Domain

http://my-IP/example.com gives 404 error.

I don’t have a problem, I wanted to share an extra step I think I figured out. (Full disclosure: I’m a 100% beginner).

This tutorial worked fine for me.
But it seemed like all I was able to serve was www.example.com/index.html. I wanted to serve all my other pages and projects from http requests like www.example.com/cool-thing-I-built.html

In case it helps anyone, and is not too obvious, you don’t have to build additional server blocks to serve your sub-pages. I don’t know what the real way is but, the simplest thing seems to be: just save cool-thing-I-built.html in the same directory as index.html.

So if you want to respond to a browser request for:

http://example.com/projects/foo.html

you just have to save foo.html in your server as

/var/www/example.com/html# ls /var/www/example.com/html/projects/foo.html 

Obviously I will go back and rename the directory so it is not ‘example.com’ but I left it like that to make it connect clearly with the above tutorial.

Just want to point out for others in case they are running into “site cannot be reached” after following all steps in this tutorial.

Make sure you have set up an A record for your domain pointing to your server IP address (the address that brings you to default Nginx landing page in this tutorial).

Read prerequisites section at this link for information on doing that.

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.