How to install nginx on ubuntu

How to install Nginx on Ubuntu

How to install Nginx on Ubuntu


Most lightweight web servers, such as NGINX, are popular because they have performance with low resource consumption. In this post, I will walk you through how to install and configure NGINX on Ubuntu 22.04 at its most basic form.

It is always good to update the package list before installing NGINX.

Step 1: Update Your System

sudo apt update
sudo apt upgrade -y

Step 2: Install NGINX The following command will install NGINX:

sudo apt install nginx -y

Once installed, you can verify the status of NGINX, which should be active and running:

sudo systemctl status nginx

Step 3: Configure Firewall Rules

If you have enabled a firewall-like UFW-you will want to let through HTTP and HTTPS traffic.

sudo ufw allow 'Nginx Full'

You can verify the status of UFW using:

sudo ufw status

Step 4: Test NGINX

To confirm that NGINX is running, fire up a browser and go to http://your_server_ip. You should be presented with the NGINX welcome page.

Step 5: Configure NGINX

Create New Server Block
Create directory for your website:

sudo mkdir -p /var/www/mywebsite.com/html

Set permissions:
sudo chown -R $USER:$USER /var/www/mywebsite.com/html
Create an HTML file:
echo "<html>
<head>
<title>Welcome to My Website</title>
</head>
<body>
<h1>Hello, NGINX!</h1>
</body>
html> |  

sudo tee /var/www/mywebsite.com/html/index.html

Create a New Server Block Configuration Create a new configuration file:

sudo nano /etc/nginx/sites-available/mywebsite.com

Add the following configuration:
server {
listen 80;
server_name mywebsite.com www.mywebsite.com;
root /var/www/mywebsite.com/html;
index index.html;

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

Enable the new server block:

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

Testing the NGINX configuration:

sudo nginx -t

If all is well, you can restart NGINX to reflect the changes:

sudo systemctl restart nginx

Step 6: Configure Domain Name

If you have registered a domain name, you will need to forward it to your server IP. You can confirm it using a DNS checker .

Step 7: Setup SSL (Optional)

To operate securely under HTTPS, you can obtain SSL certificates using Certbot .

Install Certbot:

sudo apt install certbot python3-certbot-nginx -y

Obtain and Configure SSL Certificate:

sudo certbot --nginx -d mywebsite.com -d www.mywebsite.com

You will find some prompts that you need to respond to finish the installation of the SSL.

Congratulations! You have set up and configured NGINX on Ubuntu 22.04! You are well capable of hosting your websites with ease. If you wish to have more configurations, you can go ahead and explore some other advanced features of NGINX documentation-such as reverse proxying, load balancing, and much more.

Feel free to get in touch if you have any questions or need any further assistance!

Internal Link