Nginx is a high-performance web server and reverse proxy server. Its configuration file is the core for managing websites and services. For beginners, understanding the Server block and location in the configuration file is the key to getting started.

Basic Structure of Nginx Configuration File

Nginx’s main configuration file (usually nginx.conf) consists of multiple “blocks,” forming a hierarchical configuration tree. The outermost blocks are divided into:
- Global Block: Affects basic configurations of the entire Nginx service, such as worker_processes (number of worker processes, recommended to set to the number of CPU cores) and error_log (path to error logs).
- events Block: Defines network connection-related settings, such as worker_connections (maximum connections per worker process).
- http Block: Contains multiple Server blocks and defines overall HTTP server features, such as keepalive_timeout (long connection timeout) and gzip compression.

Each block is enclosed in curly braces {}, and internal directives end with a semicolon ;.

Server Block: Core of Virtual Hosts

The Server block defines “virtual hosts,” i.e., independent configurations for different websites. A single server can run multiple websites via different domains or ports, with each website corresponding to a Server block.

Example of Server Block Structure:

server {
    listen 80;                  # Listen on port 80 (HTTP default port)
    server_name example.com;    # Match domain name (e.g., example.com or www.example.com)
    root /var/www/example;      # Root directory for website files (request path appends to root)
    index index.html;           # Default homepage (tried in sequence)
}

Key Directive Explanations:

  • listen: Specifies the port Nginx listens on (e.g., listen 8080 for port 8080).
  • server_name: Matches domains or IPs (multiple domains separated by spaces, e.g., server_name a.com b.com).
  • root: Root directory of website files; the request path is appended to root (e.g., accessing / loads /var/www/example/index.html).
  • index: Default homepage (tried in order, e.g., first index.html, then index.php).

Location Block: Route Requests by Path

The location block decides how to handle requests based on the URL path of the request (e.g., returning static files or forwarding dynamic requests).

Common Location Matching Types:

  1. Prefix Matching: location /static/ matches all paths starting with /static/ (lower priority than exact matches).
   location /static/ {
       root /var/www/static;    # Static files are in /var/www/static
       expires 7d;              # Browser cache for 7 days (reduces repeated requests)
   }

Accessing example.com/static/image.jpg returns /var/www/static/image.jpg.

  1. Exact Matching: location = / matches only the root path / (highest priority).
   location = / {
       root /var/www/example;
       index index.html;  # Return homepage for root path
   }
  1. Regular Expression Matching: ~ (case-sensitive) or ~* (case-insensitive) match paths, often for file suffixes.
   location ~* \.(jpg|png|gif)$ {  # Match image files (case-insensitive)
       root /var/www/images;
       expires 30d;  # Cache images for 30 days
   }
  1. API/Dynamic Request Matching: location /api/ matches paths starting with /api/ for forwarding to backend services (e.g., Node.js, Java).
   location /api/ {
       proxy_pass http://127.0.0.1:3000;  # Forward to backend API service
       proxy_set_header Host $host;       # Pass original domain
   }

Location Matching Priority:

Exact match (=) > Prefix match with ^~ (e.g., location ^~ /static/) > Regular prefix match > Regular expression match > Default match (/).

Comprehensive Configuration Example

A complete Server + location block configuration, including static files, dynamic requests, and API forwarding:

server {
    listen 80;
    server_name example.com;
    root /var/www/example;
    index index.html index.php;

    # 1. Static file handling (CSS, JS, images)
    location /static/ {
        root /var/www/static;
        expires 7d;  # Cache static files for 7 days
    }

    # 2. Image files (regular expression match)
    location ~* \.(jpg|png|gif)$ {
        root /var/www/images;
        expires 30d;
    }

    # 3. Dynamic requests (PHP/backend services)
    location ~ \.php$ {
        fastcgi_pass 127.0.0.1:9000;  # Forward to PHP-FPM (default 9000 port)
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;        # Include FastCGI parameters (e.g., PATH_INFO)
    }

    # 4. Single-page application (SPA) routing
    location / {
        try_files $uri $uri/ /index.html;  # Return index.html if file not found
    }
}

Configuration Validation and Activation

After modifying the configuration, verify and restart Nginx:
1. Check Configuration Syntax: nginx -t (Nginx outputs errors if configuration is invalid).
2. Reload Configuration: nginx -s reload (no service restart needed; new config takes effect).
3. Restart Service: nginx -s stop (force stop) or nginx -s quit (graceful stop) followed by nginx to start.

Summary

The core of Nginx configuration is the Server block (defines websites) and location block (routes requests by path). Beginners should start with basic configurations: listening port, domain, static file path, then gradually learn advanced features like dynamic request forwarding and caching. Practical configuration and testing will help quickly understand their interaction logic.

Xiaoye