Quantcast

How to Install Nginx on Ubuntu 22.04 LTS

NGINX is an open-source, free HTTP server software. In addition to its HTTP server capabilities, NGINX can also function as a proxy server for e-mail (IMAP, POP3, and SMTP) and a reverse proxy and load balancer for HTTP, TCP, and UDP servers. The goal behind NGINX was to create the fastest web server around, and maintaining that excellence is still a central goal of the Nginx project. NGINX consistently beats Apache and other servers in benchmarks measuring web server performance and is now the most popular used web server according to W3Tech.

In the following tutorial, you will learn to install Nginx on Ubuntu 22.04 LTS Jammy Jellyfish desktop or server with a free TLS/SSL certificate from Let’s Encrypt and some basic configuration setup with server block and Nginx file permissions.

Update Ubuntu

First, as good practice, make sure your system is up-to-date to avoid any conflicts when installing Nginx or its configuration.

sudo apt update && sudo apt upgrade

Install Nginx

By default, Nginx is featured in Ubuntu 22.04’s repository making the installation straightforward. For users that would prefer to install the Nginx mainline or a newer version of Nginx stable, please see my tutorial How to Install Nginx Mainline on Ubuntu 22.04 LTS, which covers both, then proceed back here to complete the configuration/setup.

Begin the Nginx installation using the following terminal command to install the standard Nginx webserver.

sudo apt install nginx -y

For users that want the nginx-full installation of Nginx, execute the following.

sudo apt install nginx nginx-full -y

Lastly, for the nginx-extra, you can run the following command to install these modules.

sudo apt install nginx-extras -y

Next, check the status of Nginx to make sure the service is installed correctly with no errors.

systemctl status nginx

Example output:

How to Install Nginx on Ubuntu 22.04 LTS

If, by some chance, the service is not active, use the following command to activate the Nginx service immediately.

sudo systemctl enable nginx --now

UFW Configuration

UFW is installed on Ubuntu 22.04 as the primary firewall. For users that have this active, you will need to configure some rules, or better yet, if you do not have it installed, you should look into this for a web server that will be public-facing.

First, if UFW is not installed, re-install the firewall using the following command:

sudo apt install ufw -y

Next, enable UFW with the following command.

sudo ufw enable

All incoming connections are blocked by default, and all outgoing connections are allowed.

Next, find out what applications you have installed by entering the following.

sudo ufw app list

Example output (Note an extensive list will appear of other applications as well):

How to Install Nginx on Ubuntu 22.04 LTS

Next, you can enable Nginx in HTTP (Port 80), HTTPS (Port 443), or Full, including all options.

HTTP (Port 80):

sudo ufw allow 'Nginx HTTP'

HTTP (Port 443):

sudo ufw allow 'Nginx HTTPS'

HTTP & HTTPS (Full):

sudo ufw allow 'Nginx FULL'

In the tutorial, “Nginx (Full)” was enabled.

Example output:

How to Install Nginx on Ubuntu 22.04 LTS

Confirm the firewall rules are active with the following command.

sudo ufw status

Example output:

How to Install Nginx on Ubuntu 22.04 LTS

As above, the tutorial allowed the full Nginx UFW rule option.

After UFW is configured, check to make sure you can see the Nginx landing page in your Internet Browser.

http://your_server_ip

Alternative, try the localhost.

http://localhost

If all is working well, you should land on the following page:

How to Install Nginx on Ubuntu 22.04 LTS

Set Up Site Source Directory

Nginx server blocks (similar to virtual hosts in Apache) can encapsulate configuration details and host more than one domain from a single server. In the tutorial, you will set up a domain called example.com, but you should replace this with your domain name.

When you install Nginx, it is created with a pre-installed www directory. The location is found at /var/www/html/.

First, create the directory, for example.com, as follows, using the “-p” flag to make any necessary parent directories:

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

Second, you will need to assign the owner of the directory.

sudo chown -R www-data:www-data /var/www/example.com/

Set up Test HTML page

Fourth, create a test page that you will use to confirm your Nginx server is operational.

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

Inside the nano editor and the new index file you have created, copy and paste the following for a custom test page.

<html>
 <head>
  <title>Welcome to Linuxcapable.com</title>
 </head>
 <body>
   <h1>Success!  The tutorial server block is working! Thanks Linuxcapable.com :D</h1>
 </body>
</html>

Save the file CTRL+O, then exit CTRL+X.

Create Nginx Server Block

Now, you will create the server block for your website. We will create a new server block as follows.

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

You can paste the following example code into the block. This is just an HTTP-only example for basic testing.

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

 root /var/www/example.com/;

  index index.html index.htm index.nginx-debian.html;
  server_name your_domain www.your_domain;

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

The example shows your server is listening for two server names, “example.com,” on port 80.

You will need to change the root directory to the name/location of the root directory you create.

Enable Nginx Server Block

Enable Nginx server blocks, and you must link the configuration files from sites-available to sites-enabled in your Nginx directory. This can be done with the ln -s command as follows.

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

Final Configuration & Test run

In the final stage, you will need to open your default nginx.conf file.

sudo nano /etc/nginx/nginx.conf

Then uncomment the following in the HTTP{} section of the nginx.conf configuration file:

server_names_hash_bucket_size 64;

Save the configuration with (CLTR+O) and then (CTRL+X) to exit.

Note, (server_names_hash_bucket_size) Increases the memory allocated to parsing domain names, so do not set this to an absurd number.

Next, test your Nginx to ensure it’s working before properly restarting.

sudo nginx -t

The output should be if there are no errors in the syntax:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

If your server has failed, the most common occurrence in the symlink is missing or incorrect. Navigate to your /etc/nginx/sites-enabled/ directory.

cd /etc/nginx/sites-enabled/

Now print the files using the ls command as follows.

ls

Example output:

How to Install Nginx on Ubuntu 22.04 LTS

I have created example.com.conf, which is the correct example in the example.conf, Which is incorrect, causing the Nginx service to generate an error. Remove any configuration files that will not be used, including the default file.

sudo rm default example.conf

Re-run the test; if ok, then restart.

sudo systemctl restart nginx

Now open your Internet Browser and type in the server domain name. You should see your server block is live.

How to Install Nginx on Ubuntu 22.04 LTS

Secure Webserver Files

One of the most common mistakes many users make is not fixing the permissions of files/folders. Many users even give complete read/write and execute access to the public.

Use the following command to search for all folders and files and set the most commonplace secure permissions. Make sure to change permissions on any files/directories afterward. For example, phpBB requires some folders to be 777.

sudo find /var/www/example.com/ -type d -exec chmod 755 "{}" \;
sudo find /var/www/example.com/ -type f -exec chmod 644 "{}" \;

Make sure to change /var/www/example.com/ to your root directory location.

Note that this does not make your Nginx server secure; it eliminates a prevalent risk out of many.

Secure Nginx with Let’s Encrypt SSL Free Certificate

Ideally, you would want to run your Nginx on HTTPS using an SSL certificate. The best way to do this is to use Let’s Encrypt, a free, automated, and open certificate authority run by the nonprofit Internet Security Research Group (ISRG).

First, install the certbot package with the following command.

sudo apt install python3-certbot-nginx -y

Once installed, run the following command to start the creation of your certificate:

sudo certbot --nginx --agree-tos --redirect --hsts --staple-ocsp --email you@example.com -d www.example.com

This ideal setup includes force HTTPS 301 redirects, a Strict-Transport-Security header, and OCSP Stapling. Just make sure to adjust the e-mail and domain name to your requirements.

Now your URL will be HTTPS://www.example.com instead of HTTP://www.example.com.

Note if you use the old HTTP URL, it will automatically redirect to HTTPS.

Optionally, you can set a cron job to renew the certificates automatically. Certbot offers a script that does this automatically, and you can first test to make sure everything is working by performing a dry run.

sudo certbot renew --dry-run

If everything is working, open your crontab window using the following terminal command.

sudo crontab -e

Next, please specify the time when it should auto-renew. This should be checked daily at a minimum, and if the certificate needs to be renewed, the script will not update the certificate. If you need help finding a good time to set, use the crontab.guru free tool.

00 00 */1 * * /usr/sbin/certbot-auto renew

How to Access Nginx Server Logs

Nginx Logs Directory

By default, all NGINX access/error logs, unless you have changed them, are located in the log directory, which the following command can view.

First, navigate to the logs directory and list files:

cd /var/log/nginx && ls -l

You should find the following access and error files:

Access Log:

/var/log/nginx/access.log

Error Log:

/var/log/nginx/error.log

To view logs in real-time in your terminal using the tail -f /location/of/log path command.

Example:

tail -f /var/log/nginx/access.log

Note that you may need to use sudo with the above command.

Another option is to print the last X amount of lines. For example, X is replaced with 30 to print 30 lines by adding the -n 30 flags.

sudo tail -f /var/log/nginx/access.log -n 30

These are just some examples of reading logs.

How to Configure Nginx Log Rotate

Nginx automatically installs log rotation and configures it to default to rotate daily. You can change these settings by accessing the file as shown below.

sudo nano /etc/nginx/logrotate.d/nginx

Next, you will see the same if not similar file structure. You can modify the contents here. Mostly you can change how many logs to keep or go from daily to weekly. This should be left on default unless you have specific log requirement needs for software like fail2ban monitoring.

/var/log/nginx/*.log {
  daily
  missingok
  rotate 14
  compress
  delaycompress
  notifempty
  create 0640 www-data adm
  sharedscripts
  prerotate
  if [ -d /etc/logrotate.d/httpd-prerotate ]; then \
  run-parts /etc/logrotate.d/httpd-prerotate; \
  fi \
  endscript
  postrotate
  invoke-rc.d nginx rotate >/dev/null 2>&1
  endscript
}

The main settings you will probably want to change are the following:

  • Daily – This can be changed to Weekly or Monthly. This should be kept daily, or going through the log file will be difficult.
  • Rotate 14 – This is how many logs to keep and remove, so at max, there are only 14 logs; if you only want to keep seven days’ worth of logs, change this to 7.

Its recommended not to touch any other settings unless you know what you are doing.

How to Update/Upgrade Nginx

Nginx will be updated by default when a new version hits the repositories. Before upgrading, it’s always advised to back up your Nginx directory or, at the very least, the nginx.conf file.

Back up nginx.conf (Highly Recommended).

sudo cp /etc/nginx/nginx.conf /etc/nginx/nginx-backup.conf

Back up your entire Nginx folder if you prefer.

sudo cp /etc/nginx/ /etc/nginx-bkup

Next, run the standard update command.

sudo apt update

If an upgrade is available, run the upgrade.

sudo apt upgrade 

You may be prompted this during an upgrade or installation, but manually doing this beforehand is essential. For large Nginx configurations of multiple sites, backing up to something like Github or Gitlab would be even more beneficial.

How to Remove Nginx

For users who want to remove the web server, stop the webserver.

sudo systemctl disable nginx --now

Now using the following command, remove Nginx in full.

sudo apt autoremove nginx --purge -y

Leftover files may still exist in the /etc/nginx main folder, so let us remove this directory.

sudo rm -R /etc/nginx/

Note this will clear your custom configuration files. Make sure to back up if you may use it again on Github or a similar type of service.

Comments and Conclusion

In the tutorial, you have learned to install and set up a basic Nginx configuration on your domain on Ubuntu 22.04 LTS and create a free SSL certificate using Let’s Encrypt. Overall, Nginx is the most used and popular web application software now, with every month and year surpassing taking more market share from Apache.

Some new contenders are starting to pop up, such as Openlitespeed but given these other web applications, for now, focus on specific things like WordPress. Nginx will be the go-to web application for some time.



Follow LinuxCapable.com!

Like to get automatic updates? Follow us on one of our social media accounts!