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.