Nginx is a powerful, high-performance web server that's become the preferred choice for many developers and system administrators. In this comprehensive guide, we'll walk through the complete process of installing and configuring Nginx on Ubuntu, from initial setup to advanced configuration options.
Prerequisites
Before we begin, ensure you have:
- Ubuntu 20.04 LTS or later
- Sudo privileges on your system
- Basic knowledge of Linux command line
- A domain name (optional but recommended)
Step 1: Update System Packages
First, let's ensure your system is up to date:
sudo apt update
sudo apt upgrade -y
This ensures you have the latest security patches and package versions.
Step 2: Install Nginx
Install Nginx using the package manager:
sudo apt install nginx -y
After installation, verify that Nginx is running:
sudo systemctl status nginx
You should see output indicating that Nginx is active and running.
Step 3: Configure Firewall
Configure UFW (Uncomplicated Firewall) to allow HTTP and HTTPS traffic:
sudo ufw allow 'Nginx Full'
sudo ufw enable
Check the firewall status:
sudo ufw status
Step 4: Basic Nginx Configuration
Nginx's main configuration file is located at /etc/nginx/nginx.conf. Let's examine the default configuration:
sudo nano /etc/nginx/nginx.conf
The default configuration includes:
- Worker processes configuration
- Event handling settings
- HTTP block with global settings
- Server blocks for virtual hosts
Step 5: Create Server Block (Virtual Host)
Create a new server block for your website:
sudo nano /etc/nginx/sites-available/yourdomain.com
Add the following configuration:
server {
listen 80;
listen [::]:80;
server_name yourdomain.com www.yourdomain.com;
root /var/www/yourdomain.com/html;
index index.html index.htm index.nginx-debian.html;
location / {
try_files uri uri/ =404;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
}
location ~ /\.ht {
deny all;
}
}
Step 6: Enable the Site
Create a symbolic link to enable the site:
sudo ln -s /etc/nginx/sites-available/yourdomain.com /etc/nginx/sites-enabled/
Remove the default site (optional):
sudo rm /etc/nginx/sites-enabled/default
Step 7: Test Configuration
Before restarting Nginx, test the configuration:
sudo nginx -t
If the test passes, restart Nginx:
sudo systemctl restart nginx
Step 8: Create Website Directory
Create the directory for your website:
sudo mkdir -p /var/www/yourdomain.com/html
Set proper permissions:
sudo chown -R user:user /var/www/yourdomain.com/html
sudo chmod -R 755 /var/www/yourdomain.com
Step 9: Create Sample HTML File
Create a simple HTML file to test your setup:
nano /var/www/yourdomain.com/html/index.html
Add this content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome to Your Domain</title>
</head>
<body>
<h1>Success! Nginx is working!</h1>
<p>If you can see this page, Nginx has been successfully installed and configured.</p>
</body>
</html>
Step 10: SSL/HTTPS Configuration (Optional but Recommended)
Install Certbot for Let's Encrypt SSL certificates:
sudo apt install certbot python3-certbot-nginx -y
Obtain an SSL certificate:
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
Follow the prompts to complete the SSL setup.
Advanced Configuration Options
Performance Optimization
Add these settings to your server block for better performance:
location ~* \.(css|js|png|jpg|jpeg|gif|ico|svg)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
# 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;
Load Balancing
For load balancing multiple backend servers:
upstream backend {
server 127.0.0.1:8001;
server 127.0.0.1:8002;
server 127.0.0.1:8003;
}
server {
location / {
proxy_pass http://backend;
proxy_set_header Host host;
proxy_set_header X-Real-IP remote_addr;
}
}
Troubleshooting Common Issues
Check Nginx Error Logs
sudo tail -f /var/log/nginx/error.log
Check Nginx Access Logs
sudo tail -f /var/log/nginx/access.log
Common Error Solutions
- 502 Bad Gateway: Check if your backend service is running
- 403 Forbidden: Verify file permissions and ownership
- 404 Not Found: Check your root directory path and file existence
Monitoring and Maintenance
Check Nginx Status
sudo systemctl status nginx
View Active Connections
sudo netstat -tulpn | grep :80
Monitor Performance
sudo nginx -V 2>&1 | grep -o with-http_stub_status_module
Conclusion
Congratulations! You've successfully installed and configured Nginx on Ubuntu. Your web server is now ready to serve content efficiently and securely.
Remember to:
- Regularly update Nginx and your system
- Monitor logs for any issues
- Keep your SSL certificates up to date
- Test your configuration after any changes
For production environments, consider implementing additional security measures and monitoring solutions to ensure optimal performance and reliability.