How to Install and Configure Nginx
Nginx (pronounced "engine-x") is a high-performance web server known for its stability, rich feature set, and low resource consumption. It is commonly used as a reverse proxy, load balancer, and HTTP cache.
Step 1: Update Your System
Before installing Nginx, update your package list:
sudo apt update && sudo apt upgrade -y
Step 2: Install Nginx
Install Nginx using your package manager:
sudo apt install nginx -y
After installation, start and enable Nginx:
sudo systemctl start nginx
sudo systemctl enable nginx
Step 3: Check Nginx Status
Verify that Nginx is running:
sudo systemctl status nginx
You can also visit your server’s IP address in a browser to see the default Nginx page.
Step 4: Configure Firewall
If you are using UFW, allow HTTP and HTTPS traffic:
sudo ufw allow 'Nginx Full'
Step 5: Basic Nginx Configuration
The main configuration file is located at:
/etc/nginx/nginx.conf
Server block configurations are typically stored in:
/etc/nginx/sites-available/
Create a New Server Block
sudo nano /etc/nginx/sites-available/example.com
Add the following configuration:
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com/html;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}
Enable the Server Block
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
Test Configuration
sudo nginx -t
If everything is OK, reload Nginx:
sudo systemctl reload nginx
Step 6: Create Website Files
sudo mkdir -p /var/www/example.com/html
sudo nano /var/www/example.com/html/index.html
Add a simple HTML page:
<html>
<head><title>Welcome</title></head>
<body>
<h1>Success! Nginx is working.</h1>
</body>
</html>
Step 7: Restart Nginx
sudo systemctl restart nginx
Conclusion
You have successfully installed and configured Nginx. You can now host websites, set up reverse proxies, or expand your configuration with SSL using Let's Encrypt.