Welcome to your first step in mastering Nginx! In this chapter, we're focusing on the fundamental task of serving static content – essentially, delivering files like HTML, CSS, JavaScript, and images directly to your users' browsers. At the heart of every Nginx configuration lies the 'server' block. Think of it as the dedicated virtual host for your website, telling Nginx how to handle incoming requests for a specific domain or IP address.
A 'server' block is a fundamental directive in Nginx. It defines a virtual server that can handle requests for a specific combination of IP address and port, or a specific server name (like a domain name).
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;
}
}Let's break down the key directives within this basic 'server' block:
The listen directive tells Nginx on which IP address and port to listen for incoming connections. In this case, listen 80; means Nginx will listen on all available IP addresses on port 80, the standard port for HTTP.
The server_name directive specifies the domain names or IP addresses that this server block should respond to. server_name example.com www.example.com; means Nginx will process requests where the 'Host' header matches either 'example.com' or 'www.example.com'.
The root directive defines the document root for requests. When a request comes in, Nginx will look for files within this directory. Here, root /var/www/example.com/html; sets the base directory for your website's files.
The index directive specifies the default file to serve when a directory is requested (e.g., when a user navigates to 'http://example.com/'). Nginx will try to serve these files in the order listed. index index.html index.htm; means Nginx will first look for index.html, and if it's not found, it will look for index.htm.
The location block is used to define how Nginx should process requests for specific URIs. The / location block is a catch-all for any request that doesn't match a more specific location block. The try_files directive within this block is crucial for serving static files. It attempts to find a file matching the URI ($uri), then a directory matching the URI ($uri/), and if neither is found, it returns a 404 error.
Essentially, the server block is the architect of your virtual host. It defines the boundaries of your website within Nginx, dictating which requests it should handle and how it should go about fulfilling them by finding and serving the correct files from your server's filesystem.
graph TD
A[Incoming HTTP Request] --> B{Nginx Server Block Match?}
B -- Yes --> C{Is it for example.com or www.example.com?}
C -- Yes --> D[Check 'listen' directive (port 80)]
D --> E[Determine 'root' directory: /var/www/example.com/html]
E --> F[Resolve Request URI using 'location /' and 'try_files']
F --> G[Serve Static File or Return 404]