Installing Nginx and Configuring Virtual Hosts
Nginx is a fast, lightweight web server that’s often used as an alternative to Apache. This guide covers how to install Nginx on Ubuntu and configure virtual hosts for multiple websites.
← BackStep 1: Install Nginx
sudo apt update && apt install nginx -y
Start and enable the Nginx service:
sudo systemctl enable --now nginx
Step 2: Configure a New Virtual Host
Let’s set up a virtual host for example.com
:
sudo mkdir -p /var/www/example.com/html
Set permissions:
sudo chown -R $USER:$USER /var/www/example.com/html
Create an index file:
echo "<h1>Welcome to Example.com</h1>" > /var/www/example.com/html/index.html
Create a virtual host config file:
sudo nano /etc/nginx/sites-available/example.com
Paste this inside:
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com/html;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
Enable the virtual host:
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
Test Nginx config and reload:
sudo nginx -t && sudo systemctl reload nginx
Step 3: (Optional) Update Your Hosts File
If you're working locally, map the domain to your local server:
sudo nano /etc/hosts
Add this line:
127.0.0.1 example.com
Conclusion
You’ve installed Nginx and created your first virtual host on Ubuntu. You can now serve multiple websites from a single server using Nginx virtual hosting!
← Back