What Is Server Block in Nginx: Simple Explanation and Example
server block in Nginx is a configuration section that defines how Nginx should handle requests for a specific domain or IP address. It works like a virtual host, letting you serve different websites or apps from the same server by matching the request details.How It Works
Think of a server block as a room in a big hotel. Each room has its own door number (domain or IP) and rules about who can enter and what happens inside. When a visitor (a web request) arrives, Nginx checks the door number and sends the visitor to the right room based on the server block configuration.
This lets one Nginx server handle many websites or apps by separating their settings. Each server block can specify things like the website's domain name, where its files live, and how to handle errors. This way, Nginx knows exactly what to do for each request without mixing them up.
Example
This example shows a simple server block that serves a website for example.com. It listens on port 80 and serves files from a folder.
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;
}
}When to Use
Use server blocks when you want to host multiple websites or apps on one Nginx server. For example, if you have example.com and myapp.com, you create separate server blocks for each domain. This keeps their settings and files separate.
Server blocks are also useful to set different rules for sites, like enabling HTTPS, redirecting URLs, or setting custom error pages. They help organize your server and make managing multiple sites easy and clean.
Key Points
- A server block defines how Nginx handles requests for a specific domain or IP.
- It acts like a virtual host to serve multiple sites from one server.
- You specify domain names, ports, root folders, and other settings inside it.
- Server blocks help keep sites separate and organized on the same server.