How to Install Nginx on Ubuntu 24.04, 22.04 or 20.04

This guide will demonstrate how to install Nginx on Ubuntu 24.04, 22.04, or 20.04 LTS Linux releases utilizing the command-line terminal with the APT Package manager.

Nginx is a high-performance, open-source software for web serving, reverse proxying, caching, load balancing, media streaming, and more. Its event-driven architecture enables it to provide high concurrency, without sacrificing flexibility or performance. Here are some of its key features:

  • High Efficiency: Designed to handle thousands of connections simultaneously, Nginx is known for its high performance and low memory usage.
  • Flexibility: Configuration flexibility allows it to serve a wide range of applications in various scenarios, from serving static web content to acting as a proxy server.
  • Scalability: Nginx scales effortlessly across many cores, accommodating growing traffic volumes and increasing the efficiency of the underlying hardware.
  • Security: Features like rate limiting and client request filtering help mitigate DDoS attacks and secure applications against common web threats.
  • Reverse Proxy Capabilities: It can act as a reverse proxy server for HTTP, HTTPS, SMTP, POP3, and IMAP protocols, with SSL and TLS encryption support.
  • Load Balancing: Nginx provides several load balancing methods to distribute traffic among backend servers, enhancing application availability and reliability.
  • Extensibility: With a wide range of modules available, Nginx can be extended to meet specific needs, including authentication, streaming, and more.
  • Active Community: A robust community and ecosystem support Nginx, ensuring a wealth of resources, plugins, and documentation.

Nginx’s architecture and features make it a cornerstone for modern web infrastructure, providing a reliable and efficient platform for websites and applications.

With these insights, let’s move into the technical details of how to install Nginx.

Install Nginx on Ubuntu via APT

Update Ubuntu Before Nginx Installation

Ensuring that your system is up-to-date before diving into the installation process is crucial. This practice helps prevent any conflicts during the installation or configuration of Nginx.

To update your system, run the following command:

sudo apt update && sudo apt upgrade

By default, Nginx is available in the Ubuntu repository, 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 on Ubuntu

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

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 in the future.

Verify the Nginx Installation:

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

systemctl status nginx
Screenshot showing the systemctl status command for Nginx on Ubuntu 22.04 or 20.04.
Example of ‘systemctl status’ command output for Nginx on a system running Ubuntu 22.04 or 20.04.

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 on Ubuntu

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 on Ubuntu

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 on Ubuntu

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 on Ubuntu

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 on Ubuntu

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 on Ubuntu

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 on Ubuntu

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 and related details with your actual domain name and directory paths.

Final Configuration & Test Run with Nginx on Ubuntu

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 on Ubuntu

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.

Screenshot of a successfully set up server block for Nginx on Ubuntu 22.04 or 20.04.
Visual confirmation of a successfully configured server block for Nginx on Ubuntu 22.04 or 20.04.

Additional Nginx Tips and Commands on Ubuntu

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 on Ubuntu

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, be it 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


Your Mastodon Instance
Share to...