Before upgrading Nginx, make sure you have a backup of your current configuration files. You can do this by copying the files in the /etc/nginx directory to a different safe location.
Here’s what you need to do to update Nginx on Ubuntu:
Check the initial version of Nginx you have on your Ubuntu machine:
nginx -v
The output of nginx -v command will be like this:
nginx version: nginx/1.16.1 (Ubuntu)
Make sure that your system is up-to-date, you can run the sudo apt update and sudo apt upgrade commands to do that:
sudo apt update
sudo apt upgrade
This command updates the list of available packages on your system. It retrieves the list from the repositories you’ve configured. The terminal may ask for permission for the updates to be installed, Press “Y” to allow them. The output of the terminal after running while updating will look like this:
Hit:1 http://us-east-1.ec2.archive.ubuntu.com/ubuntu jammy InRelease
Hit:2 http://us-east-1.ec2.archive.ubuntu.com/ubuntu jammy-updates InRelease
Hit:3 http://us-east-1.ec2.archive.ubuntu.com/ubuntu jammy-backports InRelease
Hit:4 http://security.ubuntu.com/ubuntu jammy-security InRelease
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
To update Nginx, you can run the command sudo apt install –only-upgrade nginx. This will install the latest version of Nginx and its dependencies. It will not remove any existing files or configuration information.
sudo apt install --only-upgrade nginx
Alternatively, you can use the following command also to update/upgrade Nginx: sudo apt upgrade nginx command:
sudo apt upgrade nginx
If the Nginx is already on the latest version you will receive a message like this: nginx is already the newest version (1.18.0-6ubuntu14.3).
This command upgrades the Nginx package to the latest version available in the package repositories. If a newer version of Nginx is available, it will be installed. Otherwise, no action will be taken.
To verify the nginx version after the update, run the following command:
nginx -v
After you upgrade Nginx, check your configuration files for syntax errors and deprecated syntax. To do this, run the command sudo nginx -t. This command will check the syntax of your configuration files and display any errors or warnings.
sudo nginx -t
If everything is good you will receive the following output:
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
You may need to restart the Nginx service after upgrading, you can do so by running sudo systemctl restart nginx:
sudo systemctl restart nginx