Introduction
Nginx is a powerful web server that can handle high traffic efficiently. In this guide, we will walk you through installing, configuring, and managing Nginx on an Ubuntu server.
Step 1 – Installing Nginx
To install Nginx, update your package list and install the server using the following commands:
sudo apt update
sudo apt install nginx
Step 2 – Adjusting the Firewall
Ensure your firewall allows HTTP traffic by enabling Nginx HTTP profile:
sudo ufw allow 'Nginx HTTP'
Verify the change:
sudo ufw status
Step 3 – Checking Nginx Status
Once installed, Nginx should be running. Check its status with:
systemctl status nginx
To test the installation, open a browser and visit:
http://your_server_ip
Step 4 – Managing the Nginx Service
Control Nginx using systemctl:
- Stop:
sudo systemctl stop nginx
- Start:
sudo systemctl start nginx
- Restart:
sudo systemctl restart nginx
- Reload (without downtime):
sudo systemctl reload nginx
- Disable auto-start:
sudo systemctl disable nginx
- Enable auto-start:
sudo systemctl enable nginx
Step 5 – Setting Up Server Blocks
To host multiple domains, create a server block:
- Make a directory for the domain:
sudo mkdir -p /var/www/example.test/html
- Set correct ownership and permissions:
sudo chown -R $USER:$USER /var/www/example.test/html
sudo chmod -R 755 /var/www/example.test - Create a test page:
sudo nano /var/www/example.test/html/index.html
Add the following:
<html>
<head>
<title>Welcome to example.test!</title>
</head>
<body>
<h1>Success! The example.test server block is working!</h1>
</body>
</html> - Configure Nginx:
sudo nano /etc/nginx/sites-available/example.test
Add this:
server {
listen 80;
listen [::]:80;
root /var/www/example.test/html;
index index.html;
server_name example.test www.example.test;
location / {
try_files $uri $uri/ =404;
}
} - Enable the configuration:
sudo ln -s /etc/nginx/sites-available/example.test /etc/nginx/sites-enabled/
- Test the configuration and restart Nginx:
sudo nginx -t
sudo systemctl restart nginx
Step 6 – Important Nginx Files and Directories
- /var/www/html – Default web directory
- /etc/nginx/nginx.conf – Main configuration file
- /etc/nginx/sites-available/ – Per-site configurations
- /etc/nginx/sites-enabled/ – Active site configurations
- /var/log/nginx/access.log – Access logs
- /var/log/nginx/error.log – Error logs
Conclusion
You have successfully installed and configured Nginx on Ubuntu. To enhance security, consider setting up an SSL certificate with Let’s Encrypt. Need a full LEMP stack? Stay tuned for more tutorials!