A server block (also called a virtual host) tells Nginx which domain to listen for and where to find your website files. This guide shows you how to set one up.
Step 1: Create your website directory
Create a directory to store your site's files (replace yourdomain.com with your actual domain):
sudo mkdir -p /var/www/yourdomain.com/html
sudo mkdir -p /var/www/yourdomain.com/logs
Set ownership to the web user:
sudo chown -R www-data:www-data /var/www/yourdomain.com/html
Step 2: Create a test index page
Create a simple HTML file to verify the site works:
sudo bash -c 'echo "<h1>Welcome to yourdomain.com</h1>" > /var/www/yourdomain.com/html/index.html'
Step 3: Create the Nginx server block
Create a new config file for your domain:
sudo nano /etc/nginx/sites-available/yourdomain.com
Paste this configuration (replace yourdomain.com and your-server-ip with your values):
server {
listen 80;
listen [::]:80;
server_name yourdomain.com www.yourdomain.com;
root /var/www/yourdomain.com/html;
index index.html index.htm;
access_log /var/www/yourdomain.com/logs/access.log;
error_log /var/www/yourdomain.com/logs/error.log;
location / {
try_files $uri $uri/ =404;
}
}
Save the file (Ctrl+O, Enter, Ctrl+X in nano).
Step 4: Enable the server block
Create a symbolic link in the sites-enabled directory:
sudo ln -s /etc/nginx/sites-available/yourdomain.com /etc/nginx/sites-enabled/yourdomain.com
Step 5: Test the configuration
Check for syntax errors:
sudo nginx -t
You should see: syntax is ok and test is successful.
Step 6: Reload Nginx
Apply the new configuration:
sudo systemctl reload nginx
Step 7: Point your domain to your server
In your domain registrar (or DNS provider), add an A record:
- Type: A
- Name: @ (or yourdomain.com)
- Value: your-server-ip
- TTL: 3600 (or default)
Also add a CNAME for www:
- Type: CNAME
- Name: www
- Value: yourdomain.com
- TTL: 3600 (or default)
Wait 5–15 minutes for DNS to propagate, then visit http://yourdomain.com in your browser.
Tips
- To disable a site without deleting it:
sudo rm /etc/nginx/sites-enabled/yourdomain.com - To re-enable it:
sudo ln -s /etc/nginx/sites-available/yourdomain.com /etc/nginx/sites-enabled/yourdomain.com - Always run
sudo nginx -tafter editing config files to catch mistakes early - Use HTTPS instead of HTTP for production sites (set up an SSL certificate with Let's Encrypt)