0
0
NginxHow-ToBeginner · 3 min read

How to Create Server Block in Nginx: Simple Guide

To create a server block in nginx, define a server block inside the configuration file, specifying the listen port and server_name. Then add directives like root to set the website folder. Finally, reload nginx to apply the changes.
📐

Syntax

A server block in Nginx defines how to handle requests for a specific domain or IP. Key parts include:

  • listen: Port number Nginx listens on (usually 80 for HTTP).
  • server_name: Domain or IP address to match requests.
  • root: Folder path where website files are stored.
  • location: Defines how to process specific URL paths.
nginx
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;
    }
}
💻

Example

This example shows a basic server block for example.com that serves static files from /var/www/example.com/html. It listens on port 80 and returns a 404 error if a file is not found.

nginx
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;
    }
}
Output
When Nginx is reloaded, requests to http://example.com will serve files from /var/www/example.com/html or return 404 if not found.
⚠️

Common Pitfalls

Common mistakes when creating server blocks include:

  • Forgetting to reload Nginx after changes (sudo nginx -s reload).
  • Not setting the correct root path, causing 404 errors.
  • Using incorrect server_name that doesn't match the requested domain.
  • Missing listen directive or using wrong port.

Always test your config with sudo nginx -t before reloading.

nginx
## Wrong example: missing listen directive
server {
    server_name example.com;
    root /var/www/example.com/html;
}

## Correct example:
server {
    listen 80;
    server_name example.com;
    root /var/www/example.com/html;
}
📊

Quick Reference

DirectivePurposeExample
listenPort Nginx listens onlisten 80;
server_nameDomain names to matchserver_name example.com www.example.com;
rootFolder with website filesroot /var/www/example.com/html;
indexDefault file to serveindex index.html index.htm;
locationURL path handlinglocation / { try_files $uri $uri/ =404; }

Key Takeaways

Define a server block with listen and server_name to create a server block.
Set the root directive to point to your website files folder.
Always test your configuration with nginx -t before reloading.
Reload Nginx after changes using sudo nginx -s reload to apply the new server block.
Check that server_name matches the domain users will request.