Too much time -nginx configuration files

As we all know, nginx architecture uses a master process to manage multiple worker processes. The master is mainly responsible for managing worker processes. For example, the leader manages multiple workers.

Worker threads are usually the same number of cores as the CPU. The purpose is to prevent the loss caused by process switching. Of course, some inter-process communication mechanisms are used between workers to achieve load balancing and other functions.

As the picture above shows, it’s clear…

As we know, the Nginx service reads the configuration file when it starts, and the subsequent behavior follows the configuration file. Nginx configuration files can be said to be similar to TXT plain text files.

After Nginx is installed by default, its configuration file is usually in the /usr/local/nginx/conf directory. Conf is the main configuration file. Config file lines that begin with # or are preceded by Spaces or tabs followed by ‘are considered comments. This is just to understand the structure of the master configuration file.

As for Nginx configuration files, whenever we need to deploy some service, need to use its reverse proxy, or other functions, we have to go to its configuration files, I believe you will check some Nginx configuration, make your service run perfectly.

Let’s talk about the structure of nginx configuration files. First, it is organized as blocks. Each block is represented by a block name and a pair of braces “{}”.

Blocks are divided into several levels. The entire configuration file is the main level, which is the largest level. In the main hierarchy, there can be event, HTTP, mail, etc. In HTTP, there is a Server block, and the server block can contain the Location block. That is, blocks can be nested, and the inner block inherits the outer block.

The basic syntax format of a configuration item is Configuration Item Name Configuration Item Value 1 Configuration Item Value 2 Configuration item Value 3… ; Each level can have its own Directive. For example, worker_processes is a main level Directive that specifies the number of Worker processes in the Nginx service.

Some directives can only be configured at one level, such as worker_processes, which can only exist in main, while others can exist at multiple levels, in which case the child block inherits the configuration of the parent block, If the child block is configured with a different instruction from the parent block, the parent block’s configuration is overwritten.

The format of the instruction is “Instruction name parameter 1 Parameter 2… Parameters N;” The parameters can be separated by any number of Spaces and a semicolon should be added at the end.

Let’s look at the block hierarchy diagram:

When the Nginx service runs, it needs to load several core modules and an event module. The configuration items supported by these modules are called basic configuration. Basic configuration items fall into the following categories:

  1. Configuration items used for debugging and locating
  2. Mandatory configuration items for normal operation
  3. Configuration items to optimize performance
  4. Event configuration item

Next, a brief look at the configuration items of each module:

Configuration items

Nginx service basic configuration items

  1. Run as daemon Nginx:
Grammar: the daemon off | on; Default: daemon on;Copy the code
  1. Error log Settings:
Syntax for path error levels: error_log /path/file level; Default: error_log logs/error.log error; /path/file is a specific file. Level indicates the log output level. The value can be: Debug info notice WARN Error crit Alert emergCopy the code

Level increases from left to right; If a log level is set, only the log whose level is greater than or equal to the specified level is displayed in the output log file.

  1. Handling special adjustment pilot:
Grammar: debug_points [stop | abort] this setting is to track the debugging Nginx;Copy the code
  1. Debug logs are generated only for specified clients:
Grammar: debug_connection [IP | DIR]Copy the code
  1. Limit the size of the coredump coredump:
Syntax: worker_rlimit_core size;Copy the code
  1. Specifies the directory where the coredump file is generated
Syntax: working_directory path;Copy the code

Configuration items that work properly

  1. Defining environment variables
Grammar: env VAR | VAR = VALUE; VAR is the variable name and VALUE is the directory.Copy the code
  1. Embed additional configuration files
Syntax: include /path/file; The include configuration item can embed other configuration files in the nginx.conf file of Nginx;Copy the code
  1. Pid file path
Syntax: pid path/file; Default: pid logs/nginx.pid; Save the pid file path of the master process.Copy the code
  1. The user and user group that the Nginx worker runs
Syntax: user username [groupname]; Default: user nobody nobody;Copy the code
  1. Specifies the maximum number of handles that the Nginx worker process can open
Grammar: worker_rlimit_nofilelimit;
Copy the code
  1. Restricted signal queue
Grammar: worker_rlimit_sigpendinglimit; Set the size of the signal queue sent by each user to Nginx.Copy the code

Optimize performance configuration items

  1. Nginx worker Number of worker processes
Syntax: worker_process number; Default: worker_process 1;Copy the code
  1. Nginx worker processes to the specified CPU kernel
Worker_cpu_affinity cpumask [cpumask...]Copy the code
  1. SSL hardware acceleration
Syntax: ssl_engine device;Copy the code
  1. How often the system call getTimeofday is executed
Syntax: timer_resolution t;Copy the code
  1. Nginx worker process priority setting
Syntax: worker_priority nice; Default: worker_priority 0;Copy the code

Event configuration item

  1. Whether to open the Accept lock
Syntax format: accept_mutex [on | off].Copy the code
  1. Lock File path
Syntax: lock_file path/file;Copy the code
  1. The delay between using the ACCEPT lock and actually establishing a connection
Accept_mutex_delay Nms;Copy the code
  1. Create new connections in batches
Syntax format: multi_accept [on | off].Copy the code
  1. Selective event model
Syntax format: use [kqueue | rtisg | epoll | / dev/poll | select | poll | eventport];Copy the code
  1. Maximum number of connections made by each worker
Syntax: worker_connections number;Copy the code

The HTTP core module is configured to serve HTTP… This is an important piece

  1. Listen on port
Grammar: listen address: port [default | default_server | [backlong = num | rcvbuf = size | sndbuf = size | accept_filter | deferred |bind| ipv6only=[on | off] | ssl]]; Default: listen: 80; Configuration block range: ServerCopy the code

To clarify:

  • Default or default_server: The server block is used as the default server block for web services. When the request does not match all the host names in the configuration file, the default virtual host is selected;
  • Backlog =num: Indicates the size of the BACKLOG queue for storing TCP new connection requests. The default value is -1.
  • Rcvbuf =size: Set the parameters of the listening handle SO_RCVBUF.
  • Sndbuf =size: Set the parameters of the listener handle SO_SNDBUF.
  • Accept_filter: Sets the accept filter, which is only available for FreeBSD operating systems.
  • Deferred: After this parameter is set, if the user initiates a TCP connection request and completes the TCP three-way handshake, but if the user does not send data, the worker process will not be woken up until data is sent.
  • Bind: binds the current port/address pair. The binding takes effect only when multiple addresses are listened on one port.
  • SSL: The connection established on the current port must be based on SSL.
  1. The host name
Syntax: server_name name[...] ; Default: server_name""; Configuration block range: ServerCopy the code
  1. Server names are stored using hash tables, and the memory occupied by each hash bucket
Syntax: server_names_hash_bucket_size size; Default: server_names_hash_bucker_size 32 | 64 | 128;Copy the code
  1. Maximum number of buckets for a hash table
Syntax: server_names_hash_max_size size; Default: server_names_hash_max_size 512; Default: server_name_in_redirect on; Configuration block range: server, HTTP, locationCopy the code
  1. Handles redirected host names
Grammar: server_name_in_redirect on | off; Default: server_name_in_redirect on; Configuration block range: server, HTTP, locationCopy the code
  1. location
The location [= | | | ~ ~ * ^ ~ | @] / uri / {} configuration block scope: serverCopy the code

Description:

Location attempts to match the/URI expression based on the URI in the user request. If the match is successful, the configuration in {} is performed to process the user request. Here are the general configuration items for Location

1. Set the syntax format of the resource path in root mode: root path;

2. Set the syntax format of the resource path as alias: alias path;

Index file… index file… ;

Error_page code [code…] [= | =answer-code] uri | @named_location;

5, is it allowed to use a error_page recursive grammar formats: recursive_error_pages [on | off].

6, try_files syntax format: try_files path1 [path2] URI;

  1. Set resource paths in root mode
Syntax: root path; Default: root HTML; Configuration block range: server, HTTP, Location,if
Copy the code
  1. Set the resource path as alias
Grammar:aliaspath; Configure the block scope: locationCopy the code
  1. Visit the home page
Syntax: index file... ; Default: index index. HTML; Configuration block range: HTTP, server, locationCopy the code
  1. Redirect the page according to the HTTP return code
Error_page code [code...]  [= | =answer-code] uri | @named_location; Configuration block range: server, HTTP, Location,if
Copy the code
  1. Whether to allow recursion using error_page
Grammar: recursive_error_pages [on | off]. Configuration block range: HTTP, server, locationCopy the code
  1. try_files
Syntax: try_files path1 [path2] uri; Configuration block range: Server, locationCopy the code
  1. HTTP package bodies are stored only in disk files
Grammar: client_body_in_file_only on | clean | off; Default: client_body_in_file_only off; Configuration block range: HTTP, server, locationCopy the code
  1. The HTTP package body is written to as much of a buffer as possible
Grammar: client_body_single_buffer on | off; Default: client_body_single_buffer off; Configuration block range: HTTP, server, locationCopy the code
  1. The size of the memory buffer that stores HTTP headers
Syntax: client_header_buffer_size SIZE; Default: client_header_BUFFer_size 1K; The configuration block ranges are HTTP and ServerCopy the code
  1. The size of the memory buffer that stores large HTTP headers
Syntax: large_client_header_buffer_size number size; Default: large_client_header_BUFFer_size 4 8K; The configuration block ranges are HTTP and ServerCopy the code
  1. The size of the buffer that stores the HTTP package body
Syntax: client_body_buffer_size size; Default: client_body_BUFFer_size 8K / 16K; Configuration block range: HTTP, server, locationCopy the code
  1. Temporary directory for storing HTTP package bodies
Client_body_temp_path dir-path [level1 [level2 [level3]]; Default: client_body_temp_path client_body_temp; Configuration block range: HTTP, server, locationCopy the code
  1. The size of the memory pool that stores the TCP connection
Syntax: connection_pool_size size; Default: connection_pool_size 256; The configuration block ranges are HTTP and ServerCopy the code
  1. The size of the memory pool that stores TCP request connections
Syntax: request_pool_size size; Default: request_pool_size 4K; The configuration block ranges are HTTP and ServerCopy the code
  1. The timeout for reading HTTP headers
Syntax: client_header_timeout time; Default: client_header_timeout 60; Configuration block range: HTTP, server, locationCopy the code
  1. The timeout for reading the HTTP package body
Syntax: client_body_timeout time; Default: client_body_timeout 60; Configuration block range: HTTP, server, locationCopy the code
  1. Timeout for sending a response
Syntax: send_timeout time; Default: send_timeout 60; Configuration block range: HTTP, server, locationCopy the code
  1. TCP connection timeout reset
Grammar: reset_timeout_connection on | off; Default: reset_timeout_connection off; Configuration block range: HTTP, server, locationCopy the code
  1. Controls how to close the TCP connection
Grammar: lingering_close off | on | always; Default: lingering_close on; Configuration block range: HTTP, server, locationCopy the code
  • Always: All user data on the connection is processed unconditionally before the connection is closed.
  • Off indicates no processing. On generally handles;
  1. lingering_time
Syntax: lingering_time time; Default: lingering_time 30s; Configuration block range: HTTP, server, locationCopy the code
  1. lingering_timeout
Syntax: lingering_timeout time; Default: lingering_time 5s; Configuration block range: HTTP, server, locationCopy the code
  1. Disable the Keepalive function for some browsers
Grammar: keepalive_disable [mise6 | safari | none]... Default: keepalive_disable mise6 Safari; Configuration block range: HTTP, server, locationCopy the code
  1. Keepalive timeout duration
Syntax: keepalive_timeout time; Default: keepalive_timeout 75; Configuration block range: HTTP, server, locationCopy the code
  1. Keepalive Maximum number of keepalive requests
Syntax: keepalive_requests n; Default: keepalive_requests 100; Configuration block range: HTTP, server, locationCopy the code
  1. tcp_nodelay
Grammar: tcp_nodelay on | off; Default: tcp_nodelay on; Configuration block range: HTTP, server, locationCopy the code
  1. tcp_nopush
Grammar: tcp_nopush on | off; Default: tcp_nopush off; Configuration block range: HTTP, server, locationCopy the code
  1. MIME Type mapping to file extensions
Grammar:type{... } Configure block range: HTTP, server, location multiple extensions can be mapped to the same MIMEtype
Copy the code
  1. The default MIME type
Syntax: default_type mime-type; Default: default_type text/plain; Configuration block range: HTTP, server, locationCopy the code
  1. type_hash_bucket_size
Syntax: type_hash_bucket_size size; Default: type_hash_bucket_size 32 | 64 | 128; Configuration block range: HTTP, server, locationCopy the code
  1. type_hash_max_size
Syntax: type_hash_max_size size; Default: type_hash_max_size 1024; Configuration block range: HTTP, server, locationCopy the code
  1. Restrict user requests by HTTP method name
Syntax: limit_except method... {... } Configuration block: Location method has the following values: GET, HEAD, POST, PUT, DELETE, MKCOL, COPY, MOVE, OPTIONS, PROPFIND, PROPPATCH, LOCK, UNLOCK, PATCHCopy the code
  1. Maximum number of HTTP request packets
Syntax: client_max_body_size size; Default: client_max_body_size 1M; Configuration block range: HTTP, server, locationCopy the code
  1. Limit the speed of requests
Syntax: limit_rate speed; Default: limit_rate 0; Configuration block range: HTTP, server, location,if0 indicates no speed limitCopy the code
  1. Limit_rate_after Limit limited after a specified time
Syntax: limit_rate_after time; Default: limit_rate_after 1M; Configuration block range: HTTP, server, location,if
Copy the code
  1. Sendfile system call
Grammar: sendfile on | off; Default: sendFile off; Configuration blocks: HTTP, Server, LocationCopy the code
  1. AIO system call
Grammar: aio on | off; Default: aio off; Configuration blocks: HTTP, Server, LocationCopy the code
  1. directio
Grammar: directio size | off; Default: directio off; Configuration blocks: HTTP, Server, LocationCopy the code
  1. directio_alignment
Syntax: directio_alignment size; Default: directio_alignment 512; Configuration blocks: HTTP, Server, LocationCopy the code
  1. Open file cache
Grammar: open_file_cache Max = N [inactive = time] | off; Default: open_file_cache off; Configuration blocks: HTTP, Server, LocationCopy the code
  1. Whether to cache error messages about open files
Grammar: open_file_cache_errors on | off; Default: open_file_cache_errors off; Configuration blocks: HTTP, Server, LocationCopy the code
  1. The minimum number of visits that are not eliminated
Syntax: open_file_cache_min_user number; Default: open_file_cache_min_user 1; Configuration blocks: HTTP, Server, LocationCopy the code
  1. How often elements in the cache are validated
Syntax: open_file_cache_valid time; Default: open_file_cache_valid 60s; Configuration blocks: HTTP, Server, LocationCopy the code
  1. Ignore invalid HTTP headers
Grammar: ignore_invalid_headers on | off; Default: ignore_invalid_headers on; Configuration block: HTTP, serverCopy the code
  1. Whether HTTP headers allow underscores
Grammar: underscores_in_headers on | off; Default: underscores_in_headers off; Configuration block: HTTP, serverCopy the code
  1. If_Modified_Since Processing policy for the header
Grammar: if_modified_since [off | exact | before] default: if_modified_since exact; Configuration blocks: HTTP, Server, LocationCopy the code
  1. Whether an error log is recorded if the file is not found
Grammar: log_not_found on | off; Default: log_not_found on; Configuration blocks: HTTP, Server, LocationCopy the code
  1. Whether to merge adjacent ‘/’
Grammar: merge_slashes on | off; Default: merge_slashes on; Configuration blocks: HTTP, Server, LocationCopy the code
  1. DNS Resolution address
Syntax: resolver address... ; Configuration blocks: HTTP, Server, LocationCopy the code
  1. Timeout period for DNS resolution
Syntax: resolver_timeout time; Default: resolver_timeout 30s; Configuration blocks: HTTP, Server, LocationCopy the code
  1. Return error page whether to specify Nginx version in server
Grammar: server_tokens on | off; Default: server_tokens on; Configuration blocks: HTTP, Server, LocationCopy the code

Nginx configuration example

Take a look at my blog’s nginx configuration:

user  www www;
worker_processes auto;
error_log  /www/wwwlogs/nginx_error.log  crit;
pid        /www/server/nginx/logs/nginx.pid;
worker_rlimit_nofile 51200;

events
    {
        use epoll;
        worker_connections 51200;
        multi_accept on;
    }

http
    {
        include       mime.types;
		include luawaf.conf;

		include proxy.conf;

        default_type  application/octet-stream;

        server_names_hash_bucket_size 512;
        client_header_buffer_size 32k;
        large_client_header_buffers 4 32k;
        client_max_body_size 50m;

        sendfile   on;
        tcp_nopush on;

        keepalive_timeout 60;

        tcp_nodelay on;

        fastcgi_connect_timeout 300;
        fastcgi_send_timeout 300;
        fastcgi_read_timeout 300;
        fastcgi_buffer_size 64k;
        fastcgi_buffers 4 64k;
        fastcgi_busy_buffers_size 128k;
        fastcgi_temp_file_write_size 256k;
		fastcgi_intercept_errors on;

        gzip on;
        gzip_min_length  1k;
        gzip_buffers     4 16k;
        gzip_http_version 1.1;
        gzip_comp_level 2;
        gzip_types     text/plain application/javascript application/x-javascript text/javascript text/css application/xml;
        gzip_vary on;
        gzip_proxied   expired no-cache no-store private auth;
        gzip_disable   "MSIE [1-6]\.";

        limit_conn_zone $binary_remote_addr zone=perip:10m;
		limit_conn_zone $server_name zone=perserver:10m;

        server_tokens off;
        access_log off;

server
    {
        listen 888;
        server_name phpmyadmin;
        index index.html index.htm index.php;
        root  /www/server/phpmyadmin;
            location ~ /tmp/ {
                return403; } error_page 404 /404.html; include enable-php.conf; location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ { expires 30d; } location ~ .*\.(js|css)? $ { expires 12h; } location ~ /\. { deny all; } access_log /www/wwwlogs/access.log; } include /www/server/panel/vhost/nginx/*.conf;All conf files for vhost nginx are loaded here, including the configuration of the following blog server
}
Copy the code

Take a look at my blog’s server configuration:

server
{
    listen 80;
    listen 443 ssl;
    server_name tc.dreamcat.ink;
    index index.php index.html index.htm default.php default.htm default.html;
    root /www/wwwroot/tc.dreamcat.ink;

    SSL-START Do not delete or modify rule 404 with comment in the next line
    error_page 404/404.html;
    ssl_certificate /etc/ssl/tc/full_chain.pem;
    ssl_certificate_key /etc/ssl/tc/private.key;
    SSL-END

    ERROR-PAGE-START  Error page configuration, can be commented, deleted, or modified
    error_page 404 /404.html;
    error_page 502 /502.html;
    ERROR-PAGE-END

    PHP-INFO-START  #PHP references the configuration, which can be commented out or modified
    include enable-php-74.conf;
    PHP-INFO-END

    REWRITE-START #URL rewrite rule reference, which will invalidate the panel setting pseudo-static rule
    include /www/server/panel/vhost/rewrite/tc.dreamcat.ink.conf;
    REWRITE-END

    The file or directory is forbidden to access
    location ~ ^/(\.user.ini|\.htaccess|\.git|\.svn|\.project|LICENSE|README.md)
    {
        return 404;
    }

    # One-click application for SSL certificate authentication directory Settingslocation ~ \.well-known{ allow all; } location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ { expires 30d; error_log off; access_log /dev/null; } location ~ .*\.(js|css)? $ { expires 12h; error_log off; access_log /dev/null; } access_log /www/wwwlogs/tc.dreamcat.ink.log; error_log /www/wwwlogs/tc.dreamcat.ink.error.log; }Copy the code

summary

This section is to understand the form of nginx configuration files, want to configure what, just look for configuration items.

reference

  • Tc. Dreamcat. Ink/archives / 26…