0
0
Nginxdevops~5 mins

Directives and blocks in Nginx - Commands & Configuration

Choose your learning style9 modes available
Introduction
Nginx uses directives and blocks to control how it handles web traffic. Directives set simple rules, while blocks group related directives together to organize configuration clearly.
When you want to set a server's listening port and domain name.
When you need to define how to handle requests for different website paths.
When you want to group settings for a website inside a server block.
When you want to control caching or security settings for a specific location.
When you want to organize your configuration for easier reading and maintenance.
Config File - nginx.conf
nginx.conf
worker_processes 1;
events {
    worker_connections 1024;
}
http {
    server {
        listen 80;
        server_name example.com;

        location / {
            root /var/www/html;
            index index.html index.htm;
        }
    }
}

worker_processes sets how many worker processes Nginx uses.

events block configures connection handling.

http block contains web server settings.

server block defines a website with its domain and port.

location block inside server sets rules for specific URL paths.

Commands
This command tests the Nginx configuration file for syntax errors before applying changes.
Terminal
sudo nginx -t
Expected OutputExpected
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful
This command reloads Nginx to apply the new configuration without stopping the server.
Terminal
sudo systemctl reload nginx
Expected OutputExpected
No output (command runs silently)
This command checks the HTTP headers returned by the server to verify it is responding correctly.
Terminal
curl -I http://example.com
Expected OutputExpected
HTTP/1.1 200 OK Server: nginx Date: Wed, 01 Jan 2025 12:00:00 GMT Content-Type: text/html Content-Length: 612 Connection: keep-alive
-I - Fetch only HTTP headers without the body
Key Concept

If you remember nothing else from this pattern, remember: directives set individual rules, and blocks group these rules to organize Nginx configuration clearly.

Common Mistakes
Placing directives outside of any block when they must be inside one.
Nginx will fail to start or ignore those directives because they are not in the correct context.
Always place directives inside the appropriate block, like 'http', 'server', or 'location'.
Forgetting to test the configuration with 'nginx -t' before reloading.
Reloading with syntax errors causes Nginx to fail or keep running old config without changes.
Run 'sudo nginx -t' to check syntax before reloading.
Summary
Use directives to set simple configuration rules in Nginx.
Use blocks to group related directives for servers and locations.
Always test your configuration with 'nginx -t' before reloading Nginx.