How to Install Nginx Latest Version on Ubuntu 20.04, Ubuntu 18.04

Previously we discussed how to install LEMP stack, which is a common software stack to host dynamic websites, on Ubuntu 18.04 LTS. However, software in Ubuntu LTS (long term support) release are often out-of-date. In this tutorial, we’re going to learn how to install Nginx latest version on Ubuntu 18.04 and Ubuntu 20.04. At the time of this writing, the latest version of Nginx is 1.17.0, released on May 21, 2019. You can see the change log here.

Installing Nginx Latest Version on Ubuntu 18.04, 20.04 from Official Nginx Repository

Nginx.org maintains a repository for Ubuntu. We can use this repository to install the latest version of Nginx. First, create a repository source file for Nginx with the following command. Nano is a command line text editor.

sudo nano /etc/apt/sources.list.d/nginx.list

Add the following two lines in the file.

deb [arch=amd64] http://nginx.org/packages/mainline/ubuntu/ bionic nginx
deb-src http://nginx.org/packages/mainline/ubuntu/ bionic nginx

ubuntu 18.04 nginx latest version amd64

If you use Ubuntu 20.04, then change bionic to focal.

deb [arch=amd64] http://nginx.org/packages/mainline/ubuntu/ focal nginx
deb-src http://nginx.org/packages/mainline/ubuntu/ focal nginx

To save the file in Nano text editor, press CTRL+O, then press Enter to confirm. Press CTRL+X to exit. In order to verify the integrity of packages downloaded from this repository, we need to import Nginx public key using the commands below.

wget http://nginx.org/keys/nginx_signing.key

sudo apt-key add nginx_signing.key

Once the repository is added to your Ubuntu 18.04 system, run the following command to update repository info.

sudo apt update

If you have installed Nginx from the default Ubuntu software repository, you need to remove it.

sudo apt remove nginx nginx-common nginx-full nginx-core

Also you may want to back up the main Nginx configuration file /etc/nginx/nginx.conf because it will be replaced with a new nginx.conf file when we later install the latest version of Nginx.

sudo cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak

Your existing server block files (aka virtual host file) will be intact. Now run the following command to install Nginx from nginx.org repository.

sudo apt install nginx

If the apt package manager asks you if you want to install a new version of /etc/nginx/nginx.conf file, you can answer No.

nginx 1.17.0 ubuntu

After Nginx is installed, test Nginx configuration.

sudo nginx -t

If the test is successful, start Nginx.

sudo systemctl start nginx

Enable autostart at boot time.

sudo systemctl enable nginx

To check the status of Nginx, run

systemctl status nginx

Output:

 nginx.service - nginx - high performance web server
   Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
   Active: active (running) since Sun 2019-05-26 21:01:10 CST; 3s ago
     Docs: http://nginx.org/en/docs/
  Process: 16159 ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.conf (code=exited, status=0/SUCCESS)
 Main PID: 16160 (nginx)
    Tasks: 2 (limit: 4915)
   CGroup: /system.slice/nginx.service
           ├─16160 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
           └─16161 nginx: worker process

May 26 21:01:10 bionic.local.domain systemd[1]: Starting nginx - high performance web server...
May 26 21:01:10 bionic.local.domain systemd[1]: Started nginx - high performance web server.

To check Nginx version, use this command:

nginx -v

Output:

nginx version: nginx/1.17.0

You can also check more detailed information with:

nginx -V

Output:

nginx ubuntu 18.04 with compat

Setting the Nginx Process User

The Nginx package from nginx.org repository set nginx as the Nginx process user which can be inferred from the first line of /etc/nginx/nginx.conf file. (If you chose to install the new version of /etc/nginx/nginx.conf file.)

user nginx;

However, the default user and group of PHP-FPM process is www-data as can be seen in /etc/php/7.4/fpm/pool.d/www.conf file.

user = www-data
group = www-data

So we need to set www-data as the Nginx process user in /etc/nginx/nginx.conf file.

sudo nano /etc/nginx/nginx.conf

Change

user nginx;

to

user www-data;

Save and close the file. Then reload Nginx.

sudo systemctl reload nginx

Including Server Block Files

By default, only files under /etc/nginx/conf.d/ directory will be included. If you also want to use server block files in sites-enabled directory, then make sure the following lines are added in the http section of nginx.conf file.

include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;

Install Certbot Nginx Plugin

If you previously installed Nginx from Ubuntu repository, then the python3-certbot-nginx package was probably removed when you install Nginx from nginx.org repository. We need to install it back so that your TLS certificate can be automatically renewed as usual.

sudo apt install python3-certbot-nginx

How to Automatically Restart Nginx

Sometimes Nginx can crash for various reasons. If you prefer to make Nginx automatically restart after a crash, then we need to edit the Nginx service unit. First, copy the original Nginx service unit to the /etc/systemd/system/ directory.

sudo cp /lib/systemd/system/nginx.service /etc/systemd/system/nginx.service

Then edit the service unit.

sudo nano /etc/systemd/system/nginx.service

Add the following line in the [service] section.

Restart=always
RestartSec=2

Like so:

[Service]
Type=forking
PIDFile=/var/run/nginx.pid
ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.conf
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s TERM $MAINPID
Restart=always
RestartSec=2

This will make Nginx try to restart itself every 2 seconds after a crash. Save and close the file. Then restart Nginx.

sudo systemctl restart nginx

Nginx Listens on Multiple IP Addresses

If your server has multiple IP addresses, you can configure it to use all available IP addresses in the virtual host config file like below.

server {
    listen 12.34.56.78:443 ssl;
    listen 12.34.56.79:443 ssl;
    listen 12.34.56.80:443 ssl;
   
    server_name example.com;

    ...
    ...
}

An interesting thing is that you can configure Nginx to listen on an IP address that you don’t own. For example, if your server doesn’t own the 12.34.56.81 IP address, you can still make Nginx listen on this IP address.

server {
    listen 12.34.56.78:443 ssl;
    listen 12.34.56.79:443 ssl;
    listen 12.34.56.80:443 ssl;
    listen 12.34.56.81:443 ssl;
   
    server_name example.com;

    ...
    ...
}

Of course, Nginx won’t be able to use this IP address, but Nginx won’t produce an error. It can still use the other IP addresses and your website will run normally.

This trick requires that there’s at least one virtual host uses the listen 443 ssl; directive. You can create a bogus virtual host like below.

server {
        server_name localhost;
        listen 80;
}
server {
        server_name localhost;
        listen 443 ssl;
        ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
        ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
        include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
        ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}

You can also allow Nginx to bind to a non-local IP address by changing a Linux kernel parameter.

sudo nano /etc/sysctl.d/60-custom.conf

Add the following line to this file.

net.ipv4.ip_nonlocal_bind=1

Save and close the file. Then apply the change.

sudo sysctl -p /etc/sysctl.d/60-custom.conf

Next Step

I hope this tutorial helped you install Nginx latest version on Ubuntu 18.04 and Ubuntu 20.04. You may also want to install the latest version of MariaDB database server on Ubuntu 18.04 and 20.04.

And if you care about security, you can set up the ModSecurity web application firewall to protect your WordPress site from hacking.

As always, if you found this post useful, then subscribe to our free newsletter to get new tips and tricks 🙂

Rate this tutorial
[Total: 8 Average: 5]

18 Responses to “How to Install Nginx Latest Version on Ubuntu 20.04, Ubuntu 18.04

  • You are awesome man. I am learning AWS and need to install latest stack on ubuntu instance.

  • Hello there,

    While typing the command:

    sudo ufw allow ‘Nginx HTTP’

    I get the below error:

    ERROR: Could not find a profile matching ‘Nginx HTTP’

    • Xiao Guo An (Admin)
      5 years ago

      Your command contains apostrophes, which should have been single quotes.

      • Thank you for replying.
        That is a mistake while typing here. I am using single quotes and getting same error

        ubuntu@ip-172-31-24-217:~$ sudo ufw allow 'Nginx HTTP'
        ERROR: Could not find a profile matching 'Nginx HTTP'
        
    • Xiao Guo An (Admin)
      5 years ago

      The content of the ‘Nginx HTTP’ profile is as follows:

      Profile: Nginx HTTP
      Title: Web Server (Nginx, HTTP)
      Description: Small, but very powerful and efficient web server
      
      Port:
        80/tcp
      

      You can run the following command to open port 80.

      sudo ufw allow 80/tcp

      You can also check out my UFW guide.

  • Thanks,
    I already open the port 80 and 443 when the above commands didn’t work. But I was wondering why that didn’t worked.

    It look like the profile does not exists in

    /etc/ufw/applications.d/

    Answer from the page https://unix.stackexchange.com/questions/460480/allow-access-to-apache-on-both-port-80-and-443-in-ubuntu-16-04 help me to create a profile.

    Anyway my problem is solved and thanks for helping.

    Is there any tutorial by you installing latest version of PHP on ngnix server in ubuntu ?

  • ubuntu18
    5 years ago

    Top tutorisal, all working. Copy past. Ubuntu 18 server.
    Saw other tutorisals – shiiit

  • beatmucit
    5 years ago

    eyvallah sağol güzel makale faydalı bilgi harika paylaşım +rep

    Thank you nice article useful information great sharing + rep

  • Parvathikaki
    5 years ago

    Ya

  • Why doesn’t the LEMP install not use this method?

    Is one better than the other?

    • Xiao Guoan (Admin)
      4 years ago

      The LEMP tutorial aims to get the user started quickly without being overwhelmed by extra information.

      For average users, it doesn’t make much difference between using the default Nginx in Ubuntu repository and using the latest Nginx version from the upstream repository. If you don’t know how to use new features in the newer Nginx version, then they are pretty much the same thing.

  • Nicholas
    3 years ago

    Thanks, great explanation of each step, and process worked perfectly for me running ubuntu 18

  • Great article, thanks so much but you know? Nginx default configuration doesn’t work for some plugins in the WordPress because it needs tunning. For example, the plugin: https://wordpress.org/plugins/woo-advanced-shipment-tracking, if you run it on the default Nginx configuration, will get the below errors when you click on “Shipping Providers”.

    2022/05/03 19:21:15 [error] 83197#83197: *27 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 37.17.197.232, server: mywebsite.com, request: "GET /wp-content/uploads/ast-shipping-providers/naqel.png?v=3.3.2 HTTP/2.0", upstream: "fastcgi://unix:/run/php/php8.0-fpm.sock", host: "mywebsite.com", referrer: "https://mywebsite.com/wp-admin/admin.php?page=woocommerce-advanced-shipment-tracking"
    
    
    
    2022/05/03 19:52:48 [warn] 83514#83514: *535 an upstream response is buffered to a temporary file /var/cache/nginx/fastcgi_temp/9/04/0000000049 while reading upstream, client: 37.17.197.232, server: mywebsite.com, request: "GET /wp-content/uploads/ast-shipping-providers/ups-germany.png?v=3.3.2 HTTP/2.0", upstream: "fastcgi://unix:/run/php/php8.0-fpm.sock:", host: "mywebsite.com", referrer: "https://mywebsite.com/wp-admin/admin.php?page=woocommerce-advanced-shipment-tracking&tab=shipping-providers"
    

    And this weird error from accessing admin panel of WordPress:

    2022/05/03 22:21:15 [error] 2020#2020: *509 FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream, client: 172.70.85.106, server: mywebsite.com, request: "GET /wp-conflg.php HTTP/2.0", upstream: "fastcgi://unix:/run/php/php8.0-fpm.sock:", host: "mywebsite.com", referrer: "http://mywebsite.com/wp-conflg.php"
    

    I believe that this article needs an extra paragraph about tuning Nginx to work with high demand plugins for processes.

    Thanks once again!! You’re doing great!

  • Alisson Araujo
    1 year ago

    Muito obrigado pelo tutorial, me ajudou demais!! Eu estava tendo problemas em instalar o nginx numa versão mais nova usando Ubuntu 22.04 e a dica sobre alterar o usuario padrão do nginx foi fundamental para o sucesso! Abraços do Brasil!

Leave a Comment

  • Comments with links are moderated by admin before published.
  • Your email address will not be published.
  • Use <pre> ... </pre> HTML tag to quote the output from your terminal/console.
  • Please use the community (https://community.linuxbabe.com) for questions unrelated to this article.
  • I don't have time to answer every question. Making a donation would incentivize me to spend more time answering questions.

The maximum upload file size: 2 MB. You can upload: image. Links to YouTube, Facebook, Twitter and other services inserted in the comment text will be automatically embedded. Drop file here