Install and Configure Nginx on Ubuntu
Nginx (pronounced "engine-x") is one of the most popular, high-performance web servers available today. It functions as a powerful reverse proxy server, load balancer, and even an HTTP cache. Known for its ability to handle a massive number of concurrent connections while using minimal resources, Nginx is trusted by some of the biggest names in tech, such as Netflix, Dropbox, and WordPress.com.
Whether you're building a personal blog, launching a web application, or managing enterprise infrastructure, understanding how to install and configure Nginx on Ubuntu can take your project to the next level. This guide walks you through everything from installation to advanced configurations on an Ubuntu system.
Table of Contents
- Introduction to Nginx
- Prerequisites
- Installing Nginx on Ubuntu
- Basic Configuration
- Managing the Nginx Service
- Creating Your First Nginx Server Block
- Enabling SSL with Let's Encrypt
- Setting Up a Reverse Proxy
- Load Balancing with Nginx
- Performance Optimization Tips
- Logging and Monitoring
- Security Best Practices
- Troubleshooting Common Errors
- Conclusion
1. Introduction to Nginx
Nginx was created by Igor Sysoev in 2004 with a focus on performance and scalability. Unlike traditional servers that spawn one process per connection, Nginx uses an event-driven architecture, making it extremely efficient under heavy loads.
Key Features of Nginx:
- High concurrency with low memory usage
- Reverse proxy with caching
- Load balancing
- HTTP/2 and IPv6 support
- TLS/SSL with SNI
- Static file serving
- Minimal configuration syntax
2. Prerequisites
To follow this guide, you’ll need:
- A machine running Ubuntu 20.04 or 22.04 (instructions are similar)
- A user with sudo privileges
- An internet connection
- A domain name (optional but helpful for SSL setup)
3. Installing Nginx on Ubuntu
Step 1: Update Your System
sudo apt update && sudo apt upgrade -y
Step 2: Install Nginx
sudo apt install nginx -y
Once installed, you can verify the installation:
nginx -v
Output:
nginx version: nginx/1.18.0 (Ubuntu)
Step 3: Adjust the Firewall
If you're using ufw:
sudo ufw allow 'Nginx Full' sudo ufw enable
Check status:
sudo ufw status
4. Basic Configuration
Nginx configurations are stored in /etc/nginx/.
Key Files and Folders:
- /etc/nginx/nginx.conf: Main configuration file.
- /etc/nginx/sites-available/: Stores available server blocks.
- /etc/nginx/sites-enabled/: Stores enabled server blocks (symlinks).
- /var/www/html: Default web root.
Default Server Block
To view it:
sudo nano /etc/nginx/sites-available/default
A minimal server block might look like:
server {
listen 80 default_server;
listen [::]:80 default_server;
root /var/www/html;
index index.html index.htm;
server_name _;
location / {
try_files $uri $uri/ =404;
}
}5. Managing the Nginx Service
Start Nginx:
sudo systemctl start nginx
Enable it at boot:
sudo systemctl enable nginx
Check status:
sudo systemctl status nginx
Reload Nginx after making config changes:
sudo systemctl reload nginx
6. Creating Your First Nginx Server Block (Virtual Host)
Let’s say you own the domain example.com.
Step 1: Create a Web Directory
sudo mkdir -p /var/www/example.com/html sudo chown -R $USER:$USER /var/www/example.com/html
Create an index.html file:
nano /var/www/example.com/html/index.html
Add basic HTML:
<html> <head><title>Welcome to Example.com</title></head> <body><h1>It works!</h1></body> </html>
Step 2: Create the Server Block
sudo nano /etc/nginx/sites-available/example.com
Add the following:
server {
listen 80;
listen [::]:80;
root /var/www/example.com/html;
index index.html;
server_name example.com www.example.com;
location / {
try_files $uri $uri/ =404;
}
}Enable it:
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
Test configuration:
sudo nginx -t
Reload:
sudo systemctl reload nginx
7. Enabling SSL with Let’s Encrypt
Step 1: Install Certbot
sudo apt install certbot python3-certbot-nginx -y
Step 2: Obtain an SSL Certificate
sudo certbot --nginx -d example.com -d www.example.com
Certbot will automatically edit your config and reload Nginx.
Verify renewal:
sudo certbot renew --dry-run
8. Setting Up a Reverse Proxy with Nginx
If you're running a Node.js app on port 3000, you can use Nginx to proxy traffic:
server {
listen 80;
server_name api.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_cache_bypass $http_upgrade;
}
}9. Load Balancing with Nginx
Nginx can act as a load balancer for multiple upstream servers.
upstream backend {
server backend1.example.com;
server backend2.example.com;
}
server {
listen 80;
server_name app.example.com;
location / {
proxy_pass http://backend;
}
}10. Performance Optimization Tips
Gzip Compression
gzip on; gzip_types text/plain application/json text/css application/javascript;
Enable Caching
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 365d;
}Increase Worker Processes
Edit /etc/nginx/nginx.conf:
worker_processes auto;
events {
worker_connections 1024;
}11. Logging and Monitoring
Default logs:
- Access log: /var/log/nginx/access.log
- Error log: /var/log/nginx/error.log
Check logs:
tail -f /var/log/nginx/access.log
Monitoring tools:
- htop
- top
- ngxtop (for real-time traffic stats)
12. Security Best Practices
Hide Nginx Version
Edit /etc/nginx/nginx.conf:
server_tokens off;
Limit Request Size
client_max_body_size 10M;
Rate Limiting
limit_req_zone $binary_remote_addr zone=mylimit:10m rate=10r/s;
server {
location / {
limit_req zone=mylimit burst=20;
}
}13. Troubleshooting Common Errors
Error: nginx: [emerg] "server" directive is not allowed here
Fix: Make sure you’re editing the right context in the config file.
Error: 403 Forbidden
Fix:
- Check permissions of the web root directory.
- Ensure index.html exists.
Error: 502 Bad Gateway
Fix:
- Check if the backend server (Node, PHP, etc.) is running.
- Check proxy configuration.
14. Conclusion
Nginx is a powerful and flexible web server that can serve static files, reverse proxy applications, balance load, and more. With this guide, you've learned:
- How to install Nginx on Ubuntu
- How to configure virtual hosts
- How to secure your site with SSL
- How to reverse proxy and load balance
- How to optimize performance and ensure security
Now that your Nginx setup is ready, you can deploy your applications, websites, or APIs with confidence and speed.