SoFunction
Updated on 2025-03-04

One article will help you understand the configuration files in Nginx

summary

Nginx (pronounced "engine-x") is a high-performance web server, reverse proxy server and load balancer, widely used in various websites and applications around the world. The power and flexibility of Nginx are mainly reflected in its configuration files. This article will introduce in detail the meaning and usage of each key field in the Nginx configuration file, and help you deeply understand how to configure Nginx to meet different needs, including common scenarios such as static resource services, reverse proxy, and load balancing.

1. Overview of Nginx configuration file structure

The configuration file of Nginx is usually located in /etc/nginx/, and its basic structure is as follows:

# Global configurationevents {
    # Event-driven configuration}

http {
    # HTTP server related configuration    server {
        # Virtual Host Configuration        location / {
            # Request processing configuration        }
    }
}

Global configuration: affects the configuration of the entire Nginx server, such as the number of worker processes, user permissions, etc.

events block: configure the way to handle connections, such as connection number limit, event-driven model, etc.

http block: Contains configurations related to handling HTTP protocols, such as server configuration, cache policies, etc.

server block: Define a virtual host that can configure listening port, domain name, SSL, etc.

location block: matches a specific URL path and defines the corresponding processing methods, such as static file services, reverse proxy, etc.

The following will introduce each field and its use in detail.

2. Global Configuration

1. worker_processes

Description: Set the number of Nginx worker processes. Usually set to the same number of CPU cores or adjust according to server load.

Example:

worker_processes auto; # Automatically set to CPU core number

2. worker_connections

Description: Set the maximum number of connections per worker process.

Example:

events {
    worker_connections 1024; # Each worker process can handle up to 1024 connections}

3. error_log

Description: Set the path and level of the error log.

Example:

error_log /var/log/nginx/ warn; # Error log level is warn

4. pid

Description: Set the process ID file path of the Nginx main process.

Example:

pid /var/run/;

3. Events block configuration

1. use

Description: Specify the event-driven model used, such as epoll (for Linux), select, etc.

Example:

events {
    use epoll; # Use epoll event-driven model}

2. accept_mutex

Description: Whether to enable mutex locks, used for load balancing connection processing.

Example:

events {
    accept_mutex on; # Enable mutex locks}

4. http block configuration

1. include

Description: Includes other configuration files for easy modular management.

Example:

http {
    include       ;
    include /etc/nginx//*.conf;
}

2. default_type

Description: Set the default MIME type.

Example:

http {
    default_type application/octet-stream;
}

3. log_format

Description: Define log format.

Example:

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
}

4. access_log

Description: Set the path and format of access logs.

Example:

http {
    access_log  /var/log/nginx/  main;
}

5. sendfile

Description: Whether to enable sendfile() system call to be used for efficient file transfer.

Example:

http {
    sendfile on;
}

6. tcp_nopush

Description: Whether to enable the TCP_NOPUSH or TCP_CORK option to improve network performance.

Example:

http {
    tcp_nopush on;
}

7. keepalive_timeout

Description: Set the timeout time to keep the connection.

Example:

http {
    keepalive_timeout 65; # Stay connected for 65 seconds}

8. types_hash_max_size

Description: Set the maximum size of the MIME type hash table.

Example:

http {
    types_hash_max_size 2048;
}

5. Server block configuration

1. listen

Description: Set the port for the server to listen.

Example:

server {
    listen 80; # Listen to port 80}

2. server_name

Description: Set the server name, which can be a domain name or an IP address.

Example:

server {
    server_name  ;
}

3. root

Description: Set the root directory of the request for static file service.

Example:

server {
    root /var/www/html;
}

4. index

Description: Set the default homepage file.

Example:

server {
    index  ;
}

5. Location block

Description: Match a specific URL path and define the corresponding processing method.

Example 1: Static File Service

server {
    listen 80;
    server_name ;
    root /var/www/html;

    location / {
        try_files $uri $uri/ =404;
    }
}

Example 2: Reverse Proxy

server {
    listen 80;
    server_name ;

    location /api/ {
        proxy_pass http://backend_server;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

Example 3: Load balancing

upstream backend {
    server ;
    server ;
    server ;
}

​​​​​​​server {
    listen 80;
    server_name ;

    location / {
        proxy_pass http://backend;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

6. rewrite

Description: Rewrite the URL.

Example:

server {
    listen 80;
    server_name ;

    location /old-url {
        rewrite ^/old-url(.*)$ /new-url$1 permanent;
    }
}

7. return

Description: Directly return the status code and redirect address.

Example:

server {
    listen 80;
    server_name ;

    location / {
        return 301 $request_uri;
    }
}

6. Detailed configuration of location block

1. try_files

Description: Try to find the file with the specified path, and if it does not exist, the specified status code is returned.

Example:

location / {
    try_files $uri $uri/ /;
}

2. alias and root

Note: Alias ​​and root can be used to specify file paths, but the difference is that alias replaces matches, while root is attached to the matches.

Example:

location /images/ {
    alias /var/www/images/;
}

location /static/ {
    root /var/www/;
}

For /images/, the actual path is /var/www/images/.

For /static/css/, the actual path is /var/www/static/css/.

3. proxy_pass

Description: Reverse proxy the request to another server.

Example:

location /api/ {
    proxy_pass http://backend_server;
}

4. proxy_set_header

Description: Set the header information of the proxy request.

Example:

location /api/ {
    proxy_pass http://backend_server;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
}

5. expires

Description: Set the HTTP cache expiration time.

Example:

location /static/ {
    expires 30d; #Cache for 30 days}

7. Summary

Nginx's configuration file is a powerful tool. By configuring various fields reasonably, it can realize multiple functions from simple static resource services to complex reverse proxying and load balancing. This article details the meaning, usage methods and examples of each key field in the Nginx configuration file, including global configuration, events block configuration, http block configuration, server block configuration, and location block configuration. By mastering these configuration methods, you can flexibly adjust Nginx's behavior according to actual needs and give full play to its high performance and flexibility.

When configuring Nginx, you need to pay attention to the following points:

1. Security: Ensure that the paths, permissions, etc. in the configuration file are set reasonably to avoid potential security vulnerabilities.

2. Performance optimization: reasonably set parameters such as the number of work processes, connections, etc., and adjust them according to server resources and load conditions.

3. Modular configuration: Use the include command to modularize the configuration file for easy maintenance and management.

4. Log management: Rationally configure log paths and levels to facilitate monitoring and analysis.

The above is a article that will help you understand the detailed content of the configuration files in Nginx. For more information about Nginx configuration files, please follow my other related articles!