Website Vidya
DeploymentStep-by-Step Guide

How to Set Up Nginx Server Blocks on Ubuntu 24.04

Learn how to set up nginx server blocks on ubuntu 24.04 with sites-available, document roots, server_name directives, syntax testing, and SSL setup.

RR
Rajesh RayLead Systems Educator
Published:
5 min read
PDF Cheat Sheet
How to Set Up Nginx Server Blocks on Ubuntu 24.04
AI Executive SummaryCORE CIS AI

5 min read

Learn how to set up nginx server blocks on ubuntu 24.04 with sites-available, document roots, server_name directives, syntax testing, and SSL setup.

Key Highlights
  • Prerequisites and Supported Releases
  • Step 1: Setting Up the Document Root Directory Structure
  • Step 2: Assigning Directory Ownership and File Permissions
Grounded in full engineering runbookCORE CIS Ai Engine

Interactive Builder for this Guide

Build your custom nginx syntax (How to Set Up Nginx Server Blocks on Ubuntu 24.04)

Generated Config Output
server {
    listen 80;
    listen [::]:80;
    server_name app.example.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name app.example.com;

    ssl_certificate /etc/letsencrypt/live/app.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/app.example.com/privkey.pem;

    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;

    gzip on;
    gzip_types text/plain text/css application/json application/javascript application/xml;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}
Production Nginx reverse proxy -> 127.0.0.1:3000 for app.example.com.
Flag-by-Flag Breakdown
server_nameBinds this virtual host to app.example.com
return 301 https://...Redirects all plain HTTP requests permanently to TLS/HTTPS
proxy_pass http://127.0.0.1:3000Forwards HTTP + WebSocket requests to local application server
X-Content-Type-Options / X-Frame-OptionsProtects users against MIME sniffing and clickjacking

When hosting multiple websites or web applications on a single cloud server, you need a mechanism to segregate configurations, document root filesystems, and security policies per domain.

In Nginx, this functionality is achieved through 'server blocks'—the high-performance equivalent of Apache Virtual Hosts.

Server blocks allow a single Nginx instance to inspect incoming HTTP/HTTPS Host request headers and seamlessly route traffic to distinct document directories, reverse proxy endpoints, or microservices.

In this tutorial, we demonstrate how to set up nginx server blocks on ubuntu 24.04 LTS step-by-step, including multi-domain directory hierarchies, configuration creation, syntax validation, and SSL encryption.

Advertisement

Prerequisites and Supported Releases

This guide is thoroughly verified on Ubuntu 24.04 LTS (Noble Numbat) & Ubuntu 22.04 LTS. The instructions apply cleanly to cloud instances (AWS EC2, Google Compute Engine, DigitalOcean, Hetzner), bare-metal servers, and local virtual machines.

Before proceeding, ensure you have the following requirements satisfied:

  • A server running Ubuntu 24.04 LTS or Ubuntu 22.04 LTS.
  • A non-root user account with sudo privileges.
  • Nginx installed and running on the server.
  • One or more registered domain names (e.g., example.com and sample.org) pointing to your server's public IP address.

Step 1: Setting Up the Document Root Directory Structure

While Nginx defaults to serving static assets from /var/www/html, hosting multiple domains requires creating independent directory trees under /var/www/.

Create a dedicated html directory for your primary domain (example.com) and an optional secondary domain (sample.org):

Advertisement

This modular directory layout keeps website assets cleanly separated:

# Create document root directories for each hosted domain:
sudo mkdir -p /var/www/example.com/html
sudo mkdir -p /var/www/sample.org/html

# Confirm directory hierarchy:
tree -d /var/www/
# Output confirms:
# /var/www/
# ├── example.com
# │   └── html
# └── sample.org
#     └── html

Step 2: Assigning Directory Ownership and File Permissions

Directories created with sudo belong to the root user by default.

Assign ownership to your active non-root user account ($USER) so you can edit website files without prepending sudo:

Next, ensure that directory permissions allow the Nginx web worker processes (running as www-data) to read files:

Create a distinctive test index.html file in each website's root directory:

Advertisement
# Assign directory ownership to your non-root user:
sudo chown -R $USER:$USER /var/www/example.com/html
sudo chown -R $USER:$USER /var/www/sample.org/html

# Set standard read and execute permissions:
sudo chmod -R 755 /var/www

# Create sample landing page for example.com:
cat << 'EOF' > /var/www/example.com/html/index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Example.com - Nginx Server Block</title>
</head>
<body>
    <h1>Success! The example.com Nginx server block is operational!</h1>
</body>
</html>
EOF

# Create sample landing page for sample.org:
cat << 'EOF' > /var/www/sample.org/html/index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sample.org - Nginx Server Block</title>
</head>
<body>
    <h1>Success! The sample.org Nginx server block is operational!</h1>
</body>
</html>
EOF

Step 3: Creating the First Nginx Server Block Configuration

On Debian and Ubuntu, Nginx uses two directories to manage configurations: sites-available (contains all defined sites) and sites-enabled (contains symlinks to actively loaded sites).

Create a new configuration file for your domain in /etc/nginx/sites-available/example.com:

Add the following clean server block definition:

# /etc/nginx/sites-available/example.com
server {
    listen 80;
    listen [::]:80;

    server_name example.com www.example.com;
    root /var/www/example.com/html;
    index index.html index.htm index.nginx-debian.html;

    location / {
        try_files $uri $uri/ =404;
    }

    # Dedicated domain access and error logs:
    access_log /var/log/nginx/example.com.access.log;
    error_log /var/log/nginx/example.com.error.log;
}

Creating the Second Server Block Configuration

Duplicate the pattern to create a configuration file for your second domain:

Add the configuration block pointing to sample.org:

# /etc/nginx/sites-available/sample.org
server {
    listen 80;
    listen [::]:80;

    server_name sample.org www.sample.org;
    root /var/www/sample.org/html;
    index index.html index.htm;

    location / {
        try_files $uri $uri/ =404;
    }

    access_log /var/log/nginx/sample.org.access.log;
    error_log /var/log/nginx/sample.org.error.log;
}

Step 4: Enabling Server Blocks and Adjusting Hash Bucket Size

Activate your new server block configurations by creating symbolic links pointing from sites-available into sites-enabled:

When adding multiple domains, Nginx might throw a hash bucket memory warning if domain names are lengthy.

Prevent this by adjusting the server_names_hash_bucket_size setting in /etc/nginx/nginx.conf:

# Enable server blocks via symbolic links:
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
sudo ln -s /etc/nginx/sites-available/sample.org /etc/nginx/sites-enabled/

# Open main Nginx configuration file to ensure hash bucket size is adequate:
# In /etc/nginx/nginx.conf, find and uncomment:
# server_names_hash_bucket_size 64;

# Quick automated check and edit using sed if commented:
sudo sed -i 's/# server_names_hash_bucket_size 64;/server_names_hash_bucket_size 64;/' /etc/nginx/nginx.conf

Step 5: Validating Nginx Syntax and Reloading the Service

Never reload or restart Nginx without testing your configuration files for syntax errors first.

Run sudo nginx -t in your terminal to verify that all directives and paths are valid:

If the test succeeds, reload Nginx with systemctl so the new server blocks take effect without dropping existing client connections:

# Test Nginx configuration syntax:
sudo nginx -t
# Expected output confirms:
# nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
# nginx: configuration file /etc/nginx/nginx.conf test is successful

# Gracefully reload Nginx to apply changes:
sudo systemctl reload nginx

# Test HTTP response for each domain using curl with Host headers:
curl -H "Host: example.com" http://localhost
# Output displays: Success! The example.com Nginx server block is operational!

curl -H "Host: sample.org" http://localhost
# Output displays: Success! The sample.org Nginx server block is operational!

Step 6: Securing Server Blocks with Let's Encrypt SSL

Once your DNS records point to your server IP address, secure both websites with trusted TLS/SSL encryption.

Install Certbot and the Python Nginx plugin, then request certificates for both domains:

Certbot automatically adjusts each server block to serve HTTPS traffic and redirect plain HTTP requests:

# Install Certbot and Nginx plugin:
sudo apt install -y certbot python3-certbot-nginx

# Obtain and deploy certificates for both domains:
sudo certbot --nginx -d example.com -d www.example.com
sudo certbot --nginx -d sample.org -d www.sample.org

# Test automated renewal dry-run:
sudo certbot renew --dry-run

Troubleshooting and Common Errors

When configuring Ubuntu servers, unexpected permission errors, network timeouts, or lock contention can occur. Review these common issues and verified resolutions:

could not build server_names_hash_bucket_size, you should increase server_names_hash_bucket_size: 32

Cause: Adding multiple domain names or long domain names exceeds the default memory allocation bucket for domain hashing.

Resolution: Uncomment or add server_names_hash_bucket_size 64; in the http block of /etc/nginx/nginx.conf.

sudo sed -i 's/# server_names_hash_bucket_size 64;/server_names_hash_bucket_size 64;/' /etc/nginx/nginx.conf && sudo nginx -t

403 Forbidden error when accessing domain

Cause: Incorrect filesystem permissions on /var/www/ or missing index.html file in document root.

Resolution: Ensure directory permissions are set to 755 and index files exist with 644 permissions.

sudo chmod -R 755 /var/www && ls -la /var/www/example.com/html

Nginx serves the default Ubuntu landing page instead of custom domain content

Cause: The default server block in /etc/nginx/sites-enabled/default is capturing requests, or DNS is not resolving Host headers correctly.

Resolution: Disable the default configuration by removing its symlink: sudo rm /etc/nginx/sites-enabled/default && sudo systemctl reload nginx.

sudo rm -f /etc/nginx/sites-enabled/default && sudo systemctl reload nginx

Security Best Practices and Hardening

Always set custom dedicated access and error log paths for each server block to isolate debugging logs per tenant.

Remove the default 000-default or default server block symlink in production to prevent unintended fallback content exposure.

Add security response headers (such as X-Content-Type-Options nosniff and X-Frame-Options SAMEORIGIN) inside your server block directives.

Deepen your Linux system administration skills with our related production-tested guides:

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
sites-available is a storage directory for all site configurations you have created, whether active or inactive. sites-enabled contains symbolic links to files in sites-available that Nginx actively loads and executes.
Remove the symbolic link from /etc/nginx/sites-enabled/ (e.g., sudo rm /etc/nginx/sites-enabled/example.com) and reload Nginx with sudo systemctl reload nginx. The original configuration remains safe in sites-available.
Yes. Each server block is completely independent; one can serve static HTML files while another routes .php requests to a fastcgi_pass PHP-FPM Unix socket.
nginx -t checks all configuration files for syntax errors and path discrepancies. If there is a typo, running nginx -t alerts you beforehand, preventing web server downtime.
RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Uncategorized•

How to Redirect HTTP to HTTPS in Nginx

If you’re running a website today and it’s still accessible over plain HTTP, you’re already behind. Modern browsers flag non-HTTPS sites as “Not Secure,” search engines favor encrypted websites, and users are far more cautious about where t...

RR
Rajesh Rai
Read More
Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout