How to Install Nginx on Ubuntu 24.04/22.04/20.04

NGINX is a high-performance web server and reverse proxy server known for its stability, rich feature set, simple configuration, and low resource consumption. It is widely used for serving static content, load balancing, and handling numerous simultaneous connections, making it a popular choice for many web applications and services.

To install NGINX on Ubuntu 24.04, 22.04, or 20.04 using the command-line terminal, you can follow straightforward steps to get your web server up and running. This guide will walk you through the process, ensuring you leverage the powerful capabilities of NGINX on your Ubuntu system.

Update Ubuntu Before Nginx Installation

It is crucial to ensure that your system is up-to-date before starting the installation process. This practice helps prevent conflicts during the installation or configuration of Nginx.

To update your system, run the following command:

sudo apt update && sudo apt upgrade

Nginx is available in the Ubuntu repository by default, simplifying the installation process. However, if you prefer to install the Nginx mainline or a newer version of Nginx stable, refer to our tutorial, “How to Install Nginx Mainline on Ubuntu,” and then return here to complete the configuration and setup.

Select Nginx Installation Type

Option 1: Install Nginx on Ubuntu via APT Command (Standard installation)

To begin the standard Nginx installation, execute the following command in the terminal:

sudo apt install nginx -y

Option 2: Install Nginx on Ubuntu via APT Command (Full installation)

For users interested in the nginx-full installation, which includes additional modules, run the following command:

sudo apt install nginx nginx-full -y

Option 3: Install Nginx-Extras on Ubuntu (Situational and Optional)

To install the nginx-extras version, which provides even more modules, execute this command:

sudo apt install nginx-extras -y

Note: Only install ‘nginx-extras’ if you intend to retain the Ubuntu version of Nginx. Avoid installing this package if you plan to update to an upstream version from Nginx.org or a LaunchPAD PPA maintained by Nginx.

Verify the Nginx Installation:

After completing the installation, verify Nginx’s status to ensure correct and error-free installation:

systemctl status nginx

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

sudo systemctl enable nginx --now

Configure UFW Firewall For Nginx

Ubuntu uses UFW (Uncomplicated Firewall) as its default firewall. For public-facing web servers, configuring UFW rules is essential for added security.

Install UFW (if not installed):

To install UFW, run the following command:

sudo apt install ufw -y

Enable UFW

Enable UFW using this command:

sudo ufw enable

By default, UFW blocks all incoming connections and allows all outgoing connections.

List Installed Applications Profiles with UFW

To view the list of installed applications, enter the following command:

sudo ufw app list

Configuring UFW Rules for Nginx:

You can configure UFW to allow connections to Nginx on HTTP (Port 80), HTTPS (Port 443), or both (Full).

HTTP (Port 80) only:

sudo ufw allow 'Nginx HTTP'

HTTPS (Port 443) only:

sudo ufw allow 'Nginx HTTPS'

Allow both HTTP and HTTPS (Full):

sudo ufw allow 'Nginx FULL'

Confirm the firewall rules are active with the following command.

sudo ufw status

Test Nginx Configuration

After configuring UFW, ensure that you can access the Nginx landing page in your web browser by navigating to your server’s IP address:

http://your_server_ip

Alternatively, try accessing the localhost:

http://localhost

If you’ve set up everything correctly, the Nginx default landing page should appear.

Create and Configure Nginx Directory For Website

Unlike Apache virtual hosts, Nginx server blocks allow you to host multiple domains on a single server by encapsulating configuration details. We’ll use the example domain example.comin this tutorial, but you should replace this with your domain name.

Nginx comes with a pre-configured www directory located at /var/www/html/.

Create a Directory for Your Domain

First, create a directory for your domain using the -p flag to create any necessary parent directories:

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

Assign Ownership For Nginx Directory

Next, assign ownership of the directory to the appropriate user and group:

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

Setup Test HTML Page For Nginx

Create a test page to confirm that your Nginx server is working correctly:

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

Inside the nano editor, paste the following HTML code to create a simple 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 with CTRL+O and exit with CTRL+X.

Create Nginx Server Block

Now, create a server block for your website:

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

Paste the following example code into the configuration file. This is a basic HTTP-only example for testing purposes:

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;
 }
}

This example configures your server to listen on port 80 for both example.com and www.example.com. Replace the root directory with the correct path you created earlier.

Enable Nginx Server Block

To enable the Nginx server block, you need to create a symbolic link from the sites-available directory to the sites-enabled directory in your Nginx installation:

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

With these steps completed, you have successfully set up an Nginx server block for your domain. Remember to replace example.com related details with your domain name and directory paths.

Final Configuration & Test Run with Nginx

In this final step, you will edit the default Nginx configuration file and test your server to ensure it’s working correctly.

Edit Nginx Configuration File

Open the default nginx.conf file:

sudo nano /etc/nginx/nginx.conf

Find the following line within the http {} section of the nginx.conf file and uncomment it:

server_names_hash_bucket_size 64;

Save the changes with CTRL+O and exit with CTRL+X.

The server_names_hash_bucket_size directive increases the memory allocated for parsing domain names. Be cautious not to set this value too high.

Test Nginx Configuration

Before restarting Nginx, test the configuration to ensure there are no syntax errors:

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

Verify Nginx Server Block

Open your web browser and enter your server’s domain name. You should see your custom test page, indicating that your server block is live and functioning correctly.

Additional Nginx Tips and Commands

Secure Nginx Webserver Files

Many users often neglect to set proper permissions for files and folders, with some even granting full read, write, and execute access to the public. Avoid this using the following commands to establish secure permissions for all files and folders. Then, adjust permissions for specific files or directories as needed afterward (for example, phpBB requires setting some folders to 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 replace /var/www/example.com/ with your root directory location.

Note: Remember that this doesn’t make your Nginx server entirely secure; it mitigates a common risk among many others.

Securing Nginx with Let’s Encrypt SSL Free Certificate

Run your Nginx server with HTTPS using an SSL certificate. Let’s Encrypt, provided by the nonprofit Internet Security Research Group (ISRG), represents one of the best options. This free, automated, open certificate authority supports secure, encrypted connections.

First, install the certbot package:

sudo apt install python3-certbot-nginx

Once installed, initiate the certificate creation process:

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

This setup includes force HTTPS 301 redirects, a Strict-Transport-Security header, and OCSP Stapling. Make sure to adjust the email and domain name as needed.

Your URL will now use HTTPS (e.g., https://www.example.com) instead of HTTP. If you still use the old HTTP URL, it will automatically redirect to HTTPS.

Optional: Auto-Renew Certificates For Nginx

To renew certificates automatically, set up a cron job. Certbot offers a script for this purpose, and you can test its functionality with a dry run:

sudo certbot renew --dry-run

If everything works as expected, open your crontab using the following command:

sudo crontab -e

Specify the auto-renewal process time, checking daily at a minimum. If the certificate requires renewal, the script will update it:

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

Access Nginx Server Logs

Nginx Logs Directory

Nginx stores its logs in a default directory unless you’ve specified a different location. You can view the logs using the following commands.

First, navigate to the logs directory and list the files:

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

You should find the following access and error files:

Access Log Nginx Location:

/var/log/nginx/access.log

Error Log Nginx Location:

/var/log/nginx/error.log

To monitor logs in real-time, use the tail -f /location/of/log command:

Example command:

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

Note that you might need to use sudo with this command.

To display a specific number of lines (e.g., the last 30 lines), add the -n 30 flag:

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

These are just a few examples of how to read logs.

Configure Nginx Log Rotation

Nginx automatically sets up log rotation with daily rotations by default. To modify these settings, access the file:

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

The file includes adjustable settings like rotation frequency and log retention quantity. Retain the default settings unless specific log requirements for monitoring software like fail2ban necessitate changes.

The most common settings to change are:

  • Daily: This can be changed to Weekly or Monthly, but daily is recommended for easier log file management.
  • Rotate 14: Determines the number of logs to keep. Change this to 7 to store only one week’s worth of logs.

Avoid altering other settings unless you’re sure about their functions.

/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
}

Update Nginx

Nginx updates automatically when a new version is available in the repositories. Before upgrading, back up your Nginx directory or, at a minimum, the nginx.conf file.

To back up nginx.conf:

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

To back up the entire Nginx folder:

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

Next, run the standard update command:

sudo apt update

If an upgrade is available, execute the upgrade:

sudo apt upgrade 

Backing up before upgrading is crucial, especially for large Nginx configurations. Consider using Github or Gitlab for additional backup options.

Remove Nginx

If you decide to remove the web server, first stop it:

sudo systemctl disable nginx --now

Then, use the following command to remove Nginx altogether:

sudo apt remove nginx

Some leftover files might remain in the /etc/nginx folder. Remove this directory with:

sudo rm -R /etc/nginx/

This action will delete your custom configuration files, so back them up if you use them again (e.g., with Github or a similar service).

Conclusion

With the steps outlined in our guide, you should now have Nginx successfully installed on your Ubuntu server, 24.04, 22.04, or 20.04. You’ve learned the installation process and how to set up a basic configuration to get your server running. Regular updates and security checks are key to maintaining a robust server. Don’t hesitate to dive deeper into Nginx’s extensive features to optimize your setup further.

Leave a Comment