How to Install Nginx on Ubuntu 20.04 in Minutes (Step-by-Step Guide) - Techvblogs

How to Install Nginx on Ubuntu 20.04 in Minutes (Step-by-Step Guide)

Install Nginx on Ubuntu 20.04 with this easy guide. Boost your server speed and security now.


Suresh Ramani - Author - Techvblogs
Suresh Ramani
 

8 hours ago

TechvBlogs - Google News

Learning how to install Nginx Ubuntu 20.04 is essential for anyone looking to set up a high-performance web server. This comprehensive guide walks you through the complete process of installing, configuring, and securing Nginx on your Ubuntu 20.04 system in just a few minutes.

Whether you’re a beginner setting up your first web server or an experienced developer deploying production applications, this tutorial provides clear, step-by-step instructions to install Nginx Ubuntu 20.04 successfully. You’ll learn everything from basic installation to advanced configurations that will help you get the most out of your Nginx web server.

Prerequisites for Installing Nginx

Before you install Nginx Ubuntu 20.04, ensure your system meets the basic requirements and has the necessary components configured properly.

Update Ubuntu 20.04 Packages

Start by updating your package repository and existing packages to ensure you have the latest security patches and software versions.

Update System Packages:

# Update package index
sudo apt update

# Upgrade existing packages
sudo apt upgrade -y

# Check Ubuntu version
lsb_release -a

# Verify available disk space
df -h

# Check system memory
free -h

Updating packages before you install Nginx Ubuntu 20.04 prevents compatibility issues and ensures you get the most stable version available. The upgrade process typically takes 2-5 minutes depending on your system and internet connection speed.

Install Essential System Tools:

# Install curl for testing
sudo apt install curl -y

# Install wget for downloading files
sudo apt install wget -y

# Install text editors
sudo apt install nano vim -y

# Install network tools
sudo apt install net-tools -y

Install Essential Dependencies

Although Nginx has minimal dependencies, installing essential packages ensures smooth operation and provides useful tools for server management.

Required Dependencies:

# Install build essentials
sudo apt install build-essential -y

# Install software properties common
sudo apt install software-properties-common -y

# Install APT transport HTTPS
sudo apt install apt-transport-https -y

# Install CA certificates
sudo apt install ca-certificates -y

# Install GNU Privacy Guard
sudo apt install gnupg -y

These dependencies support secure package installation and provide essential tools you’ll need when you install Nginx Ubuntu 20.04 and configure it for production use.

Configure UFW Firewall for Nginx

Setting up firewall rules before installation ensures your Nginx server is accessible while maintaining security best practices.

Configure UFW Firewall:

# Check UFW status
sudo ufw status

# Enable UFW if not already enabled
sudo ufw enable

# Allow SSH (important for remote access)
sudo ufw allow ssh
sudo ufw allow 22

# Allow HTTP traffic
sudo ufw allow 'Nginx HTTP'
sudo ufw allow 80

# Allow HTTPS traffic
sudo ufw allow 'Nginx HTTPS'
sudo ufw allow 443

# Allow Nginx Full (HTTP + HTTPS)
sudo ufw allow 'Nginx Full'

# Verify firewall rules
sudo ufw status numbered

Understanding UFW Nginx Profiles:

When you install Nginx Ubuntu 20.04, the package automatically creates UFW application profiles that make firewall management easier:

  • Nginx HTTP: Opens port 80 for unencrypted web traffic
  • Nginx HTTPS: Opens port 443 for encrypted web traffic
  • Nginx Full: Opens both ports 80 and 443

Step-by-Step Installation Guide

The actual installation process to install Nginx Ubuntu 20.04 is straightforward and typically completes in under a minute.

Install Nginx Using APT

Ubuntu’s default package repository includes a stable version of Nginx that’s perfect for most use cases.

Install Nginx Package:

# Install Nginx from Ubuntu repository
sudo apt install nginx -y

# Check installed version
nginx -v

# Verify installation location
which nginx

# Check Nginx package information
apt show nginx

Alternative: Install Latest Nginx Version:

If you need the latest features, you can install from the official Nginx repository:

# Add Nginx signing key
curl -fsSL https://nginx.org/keys/nginx_signing.key | sudo gpg --dearmor -o /usr/share/keyrings/nginx-archive-keyring.gpg

# Add Nginx repository
echo "deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] http://nginx.org/packages/ubuntu focal nginx" | sudo tee /etc/apt/sources.list.d/nginx.list

# Update package index
sudo apt update

# Install latest Nginx
sudo apt install nginx -y

Verify Nginx Installation

After you install Nginx Ubuntu 20.04, verify that everything is working correctly before proceeding with configuration.

Check Nginx Status:

# Check if Nginx is running
sudo systemctl status nginx

# Test Nginx configuration
sudo nginx -t

# Display Nginx version and configuration options
nginx -V

# Check listening ports
sudo netstat -tulpn | grep nginx

Test Nginx in Browser:

# Test locally with curl
curl http://localhost

# Test with specific IP
curl http://your-server-ip

# Check response headers
curl -I http://localhost

You should see the default Nginx welcome page, which confirms that you successfully install Nginx Ubuntu 20.04. The page displays “Welcome to nginx!” with additional information about configuration.

Enable and Start Nginx Service

Configure Nginx to start automatically on system boot and manage the service properly.

Manage Nginx Service:

# Start Nginx service
sudo systemctl start nginx

# Enable Nginx to start on boot
sudo systemctl enable nginx

# Check if auto-start is enabled
sudo systemctl is-enabled nginx

# View Nginx service details
sudo systemctl show nginx

# Check service dependencies
systemctl list-dependencies nginx

Nginx Service Commands:

# Start Nginx
sudo systemctl start nginx

# Stop Nginx
sudo systemctl stop nginx

# Restart Nginx (stops then starts)
sudo systemctl restart nginx

# Reload Nginx configuration (no downtime)
sudo systemctl reload nginx

# Check Nginx status
sudo systemctl status nginx

The reload command is particularly useful because it applies configuration changes without dropping existing connections, making it perfect for production environments.

Basic Nginx Configuration

Understanding Nginx configuration is crucial for customizing your web server after you install Nginx Ubuntu 20.04.

Nginx File Structure in Ubuntu 20.04

Familiarize yourself with the Nginx directory structure to manage your server effectively.

Key Nginx Directories:

# Main configuration file
/etc/nginx/nginx.conf

# Available site configurations
/etc/nginx/sites-available/

# Enabled site configurations
/etc/nginx/sites-enabled/

# Configuration snippets
/etc/nginx/snippets/

# Log files
/var/log/nginx/

# Web root directory
/var/www/html/

# Nginx binary
/usr/sbin/nginx

Explore Configuration Structure:

# View main configuration
sudo nano /etc/nginx/nginx.conf

# List available sites
ls -la /etc/nginx/sites-available/

# List enabled sites
ls -la /etc/nginx/sites-enabled/

# Check web root contents
ls -la /var/www/html/

# View default site configuration
sudo nano /etc/nginx/sites-available/default

Set Up Virtual Hosts

Virtual hosts allow you to host multiple websites on a single server after you install Nginx Ubuntu 20.04.

Create Your First Virtual Host:

# Create directory for your website
sudo mkdir -p /var/www/example.com/html

# Set proper ownership
sudo chown -R $USER:$USER /var/www/example.com/html

# Set proper permissions
sudo chmod -R 755 /var/www/example.com

# Create a sample index page
sudo nano /var/www/example.com/html/index.html

Sample HTML Content:

<!DOCTYPE html>
<html>
<head>
    <title>Welcome to Example.com</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; }
        h1 { color: #333; }
    </style>
</head>
<body>
    <h1>Welcome to Example.com</h1>
    <p>This is a sample page served by Nginx on Ubuntu 20.04.</p>
    <p>Server is running successfully!</p>
</body>
</html>

Configure Server Blocks

Server blocks are Nginx’s version of virtual hosts, allowing you to serve multiple domains from one server.

Create Server Block Configuration:

# Create new site configuration
sudo nano /etc/nginx/sites-available/example.com

Basic Server Block Configuration:

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

    root /var/www/example.com/html;
    index index.html index.htm index.nginx-debian.html;

    server_name example.com www.example.com;

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

    # Logging
    access_log /var/log/nginx/example.com.access.log;
    error_log /var/log/nginx/example.com.error.log;

    # Security headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "no-referrer-when-downgrade" always;
    add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;

    # Disable server tokens
    server_tokens off;
}

Enable Server Block:

# Create symbolic link to enable site
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/

# Test configuration
sudo nginx -t

# Reload Nginx
sudo systemctl reload nginx

# Verify the site is enabled
ls -la /etc/nginx/sites-enabled/

Securing Nginx on Ubuntu 20.04

Security should be a priority when you install Nginx Ubuntu 20.04, especially for production environments.

Install SSL Using Let’s Encrypt

Let’s Encrypt provides free SSL certificates that encrypt traffic between your server and visitors.

Install Certbot:

# Install snapd (if not already installed)
sudo apt install snapd -y

# Install certbot via snap
sudo snap install --classic certbot

# Create symbolic link
sudo ln -s /snap/bin/certbot /usr/bin/certbot

# Verify certbot installation
certbot --version

Obtain SSL Certificate:

# Get certificate for your domain
sudo certbot --nginx -d example.com -d www.example.com

# Alternative: Certificate only (manual installation)
sudo certbot certonly --nginx -d example.com -d www.example.com

# List all certificates
sudo certbot certificates

# Test automatic renewal
sudo certbot renew --dry-run

Redirect HTTP to HTTPS

After installing SSL certificates, configure automatic HTTPS redirects for better security.

Manual HTTPS Redirect Configuration:

# HTTP server block (redirects to HTTPS)
server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;
    return 301 https://$server_name$request_uri;
}

# HTTPS server block
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    
    root /var/www/example.com/html;
    index index.html index.htm;
    
    server_name example.com www.example.com;

    # SSL Configuration
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    ssl_trusted_certificate /etc/letsencrypt/live/example.com/chain.pem;

    # SSL Settings
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;

    # Security headers
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
    
    location / {
        try_files $uri $uri/ =404;
    }
}

Test Nginx SSL Configuration

Verify your SSL setup is working correctly and secure.

SSL Testing Commands:

# Test SSL certificate
openssl s_client -connect example.com:443 -servername example.com

# Check certificate expiration
openssl s_client -connect example.com:443 -servername example.com 2>/dev/null | openssl x509 -noout -dates

# Test HTTPS redirect
curl -I http://example.com

# Test HTTPS response
curl -I https://example.com

# Check SSL configuration
sudo nginx -t

Online SSL Testing:

Use these online tools to verify your SSL configuration:

Performance Optimization

Optimize your Nginx server for better performance after you install Nginx Ubuntu 20.04.

Enable Gzip Compression

Gzip compression reduces bandwidth usage and improves page load times.

Configure Gzip Compression:

# Edit main configuration
sudo nano /etc/nginx/nginx.conf

Gzip Configuration Block:

# Gzip Settings
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_proxied any;
gzip_comp_level 6;
gzip_types
    text/plain
    text/css
    text/xml
    text/javascript
    application/json
    application/javascript
    application/xml+rss
    application/atom+xml
    image/svg+xml;

Configure Caching Headers

Proper caching headers improve performance by reducing server load and speeding up repeat visits.

Caching Configuration:

# Browser caching
location ~* \.(jpg|jpeg|png|gif|ico|svg)$ {
    expires 1y;
    add_header Cache-Control "public, immutable";
}

location ~* \.(css|js)$ {
    expires 1y;
    add_header Cache-Control "public";
}

location ~* \.(pdf)$ {
    expires 30d;
    add_header Cache-Control "public";
}

# Disable caching for dynamic content
location ~* \.(php|html)$ {
    expires -1;
    add_header Cache-Control "no-cache, no-store, must-revalidate";
    add_header Pragma "no-cache";
}

Use Nginx with PHP-FPM

If you’re serving PHP applications, configure Nginx to work with PHP-FPM for optimal performance.

Install PHP-FPM:

# Install PHP-FPM
sudo apt install php-fpm php-mysql php-curl php-gd php-mbstring php-xml php-zip -y

# Check PHP-FPM status
sudo systemctl status php8.0-fpm

# Enable PHP-FPM
sudo systemctl enable php8.0-fpm

Nginx PHP Configuration:

server {
    listen 80;
    root /var/www/example.com;
    index index.php index.html index.htm;
    server_name example.com;

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

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php8.0-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.ht {
        deny all;
    }
}

Nginx Maintenance and Monitoring

Regular maintenance ensures your Nginx server remains secure and performs optimally after you install Nginx Ubuntu 20.04.

View and Understand Nginx Logs

Nginx logs provide valuable insights into server performance and potential issues.

Log File Locations:

# Access logs (successful requests)
sudo tail -f /var/log/nginx/access.log

# Error logs (server errors)
sudo tail -f /var/log/nginx/error.log

# Site-specific logs
sudo tail -f /var/log/nginx/example.com.access.log

# View log statistics
sudo cat /var/log/nginx/access.log | awk '{print $1}' | sort | uniq -c | sort -nr

Log Analysis Commands:

# Find most requested pages
sudo awk '{print $7}' /var/log/nginx/access.log | sort | uniq -c | sort -nr | head -10

# Find top IP addresses
sudo awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -nr | head -10

# Find 404 errors
sudo grep "404" /var/log/nginx/access.log

# Find server errors (5xx)
sudo grep "50[0-9]" /var/log/nginx/access.log

Restart and Reload Nginx Safely

Understanding when to restart vs reload Nginx prevents unnecessary downtime.

Nginx Service Management:

# Test configuration before applying changes
sudo nginx -t

# Reload configuration (preferred for live sites)
sudo systemctl reload nginx

# Restart service (when reload isn't sufficient)
sudo systemctl restart nginx

# Check if reload was successful
sudo systemctl status nginx

# Force reload if process is stuck
sudo pkill -HUP nginx

Best Practices:

  • Always test configuration with nginx -t before reloading
  • Use reload instead of restart for configuration changes
  • Use restart only when installing modules or major updates

Troubleshoot Common Nginx Issues

Identify and resolve common problems that may occur after you install Nginx Ubuntu 20.04.

Common Issues and Solutions:

Issue 1: Configuration Test Fails

# Check syntax errors
sudo nginx -t

# Check for conflicting server blocks
sudo nginx -T | grep server_name

# Verify file permissions
ls -la /etc/nginx/sites-enabled/

Issue 2: Nginx Won’t Start

# Check if another service is using port 80
sudo netstat -tulpn | grep :80

# Check system logs
sudo journalctl -u nginx.service

# Verify Nginx binary
which nginx
nginx -v

Issue 3: Permission Denied Errors

# Fix web directory permissions
sudo chown -R www-data:www-data /var/www/

# Set proper directory permissions
sudo find /var/www/ -type d -exec chmod 755 {} \;

# Set proper file permissions
sudo find /var/www/ -type f -exec chmod 644 {} \;

Advanced Topics

Explore advanced Nginx features to maximize your server’s capabilities after you install Nginx Ubuntu 20.04.

Load Balancing with Nginx

Configure Nginx as a load balancer to distribute traffic across multiple backend servers.

Basic Load Balancer Configuration:

upstream backend {
    server 192.168.1.10:80;
    server 192.168.1.11:80;
    server 192.168.1.12:80;
}

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://backend;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

Reverse Proxy Configuration

Use Nginx as a reverse proxy to serve applications running on different ports.

Reverse Proxy Example:

server {
    listen 80;
    server_name app.example.com;

    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_cache_bypass $http_upgrade;
    }
}

Nginx with Docker on Ubuntu 20.04

Run Nginx in Docker containers for easier deployment and scaling.

Docker Nginx Setup:

# Create Dockerfile
cat > Dockerfile << EOF
FROM nginx:alpine
COPY nginx.conf /etc/nginx/nginx.conf
COPY html/ /usr/share/nginx/html/
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
EOF

# Build Docker image
sudo docker build -t my-nginx .

# Run Nginx container
sudo docker run -d -p 80:80 --name nginx-server my-nginx

# Check container status
sudo docker ps

Docker Compose Configuration:

version: '3.8'
services:
  nginx:
    image: nginx:alpine
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf
      - ./html:/usr/share/nginx/html
      - ./ssl:/etc/nginx/ssl
    restart: unless-stopped

Key Takeaways

Successfully completing this guide means you now know how to install Nginx Ubuntu 20.04 and configure it for various use cases. From basic installation to advanced configurations, you have the knowledge to deploy and maintain a robust web server.

Essential points to remember:

  • Always update your system before installation
  • Configure firewall rules to secure your server
  • Use Let’s Encrypt for free SSL certificates
  • Implement security headers and best practices
  • Monitor logs regularly for issues and performance insights
  • Test configuration changes before applying them to production

Best practices for Nginx on Ubuntu 20.04:

  • Keep Nginx and Ubuntu updated with security patches
  • Use reload instead of restart for configuration changes
  • Implement proper backup strategies for configuration files
  • Monitor server performance and optimize as needed
  • Document your configuration changes for future reference

By following this comprehensive guide, you’ll have a secure, optimized Nginx web server running on Ubuntu 20.04 that can handle everything from simple static websites to complex web applications with high performance and reliability.

Comments (0)

Comment


Note: All Input Fields are required.