Detailed explanation of common configuration of nginx

Keywords: Nginx

1, nginx configuration file structure:

...              #Global block events {         #events block   ...} http      #http block{    ...   #http Global block    server        #server block    {        ...       #server Global block        location [PATTERN]   #location block        {            ...        }        location [PATTERN]        {            ...        }    }    server    {      ...    }    ...     #http global block}

1. Global block: configure instructions that affect nginx global. Generally, there are user groups running nginx server, pid storage path of nginx process, log storage path, introduction of configuration file, number of worker process es allowed to be generated, etc.

2. events block: the configuration affects the nginx server or the network connection with the user. There is the maximum number of connections per process, which event driven model is selected to process connection requests, whether multiple network connections are allowed to be accepted at the same time, and starting multiple network connection serialization.

3. http block: it can nest multiple server s, configure most functions such as proxy, cache and log definition, and configure third-party modules. Such as file import, MIME type definition, log customization, whether to use sendfile to transfer files, connection timeout, number of single connection requests, etc.

4. server block: configure the relevant parameters of the virtual host. There can be multiple servers in one http.

5. location block: configure the routing of requests and the processing of various pages.

2, Detailed description of configuration file:

########### Each instruction must end with a semicolon.##################user administrator administrators;  #Configure users or groups. The default is nobody nobody. #worker_processes 2;  #The number of processes allowed to be generated. The default is 1#pid /nginx/pid/;   #appoint nginx Process running file storage address error_log log/error.log debug;  #Make log path and level. This setting can be put into the global block, http Block, server Block at this level: debug|info|notice|warn|error|crit|alert|emergevents {    accept_mutex on;   #Set the network connection serialization to prevent group panic. The default is on    multi_accept on;  #Set whether a process accepts multiple network connections at the same time. The default is off    #use epoll;      #Event driven model, select|poll|kqueue|epoll|resig|/dev/poll|eventport    worker_connections  1024;    #The maximum number of connections is 512 by default}http {include       mime.types;   #File extension and file type mapping table#gzip  on; Support online real-time compression of output data stream.    default_type  application/octet-stream; #The default file type is text/plain    #access_log off; #Cancel service log       log_format myFormat '$remote_addr–$remote_user [$time_local] $request $status $body_bytes_sent $http_referer $http_user_agent $http_x_forwarded_for'; #Custom format    access_log log/access.log myFormat;  #combined Is the default value for the log format    sendfile on;   #allow sendfile Transfer files by default off,Can be in http Block, server Block, location Block.    sendfile_max_chunk 100k;  #The number of transfers per call of each process cannot be greater than the set value. The default value is 0, that is, there is no upper limit.    keepalive_timeout 65;  #Connection timeout, 75 by default s,Can be in http,server,location Block.     upstream mysvr {        server;      server backup;  #Hot standby    }    error_page 404; # Error page server {keepalive_requests 120; # maximum number of single connection requests. Listen 4545; # listening port server_name; # listening address location ~ * ^+$ {# request url filtering, regular matching, ~ is case sensitive, ~ * is case insensitive. #root path; # root directory #index vv.txt; # set the default page proxy #u pass http://mysvr ; # request to turn to mysvr defined server list deny; # rejected ip allow; # allowed ip   }    }}

The above is the basic configuration of nginx. Note the following:

1,1.$remote_addr   With $http_x_forwarded_for   To record the ip address of the client;   2.$remote_user  : Used to record the client user name;   3.$time_local  : Used to record access time and time zone; 4.$request  : The url and HTTP protocol used to record the request;

  5.$status  : Used to record request status; Success is 200,   6.$body_bytes_s ent  : Record the content size of the file body sent to the client; 7.$http_referer  : Used to record the links accessed from that page;   8.$http_user_agent  : Record the relevant information of the client browser;

2. Group shock: when a network connection arrives, multiple sleeping processes are awakened by colleagues, but only one process can get the link, which will affect the system performance.

3. Each instruction must end with a semicolon.

3, Common configuration:

3.1. Global configuration

user nobody nobody;worker_processes 2;error_log logs/error.log notice;pid logs/;worker_rlimit_nofile 65535; events{use epoll;worker_connections 65536;}

The meaning of each configuration option is explained as follows:

·         User is a main module instruction that specifies the running user and user group of the Nginx Worker process. It is run by the nobody account by default.

·         worker_processes is a main module instruction that specifies the number of processes to be started by Nginx. Each Nginx process consumes an average of 10M~12M memory. It is recommended to specify the same number of CPU s.

·         error_log is a main module instruction used to define the global error log file. The log output levels include debug, info, notice, warn, error and crit. Among them, the debug output log is the most detailed, and the crit output log is the least.

·         pid is a main module instruction, which is used to specify the storage file location of process pid.

worker_rlimit_nofile is used to bind worker process and CPU. Linux kernel 2.4 or above is available.

3.2.HTTP server configuration

http{include conf/mime.types;default_type application/octet-stream;log_format main '$remote_addr - $remote_user [$time_local] ''"$request" $status $bytes_sent ''"$http_referer" "$http_user_agent" ''"$gzip_ratio"';log_format download '$remote_addr - $remote_user [$time_local] ''"$request" $status $bytes_sent ''"$http_referer" "$http_user_agent" ''"$http_range" "$sent_http_content_range"';client_max_body_size 20m;client_header_buffer_size 32K;large_client_header_buffers 4 32k;Sendfile on;tcp_nopush on;tcp_nodelay on;keepalive_timeout 60;client_header_timeout 10;client_body_timeout 10;send_timeout 10;

l    Include is a main module instruction to set the files contained in the configuration file, which can reduce the complexity of the main configuration file. Similar to the include method in Apache.

l    default_type belongs to the HTTP core module instruction. Here, the default type is set to binary stream, that is, this method is used when the file type is not defined. For example, when the PHP environment is not configured, Nginx will not be parsed. At this time, when accessing the PHP file with a browser, a download window will appear.

l    log_format is the HttpLog module instruction of Nginx, which is used to specify the output format of Nginx log. main is the name of this log output format, which can be found in access below_ Log instruction.

l    client_max_body_size is used to set the maximum number of single file bytes allowed to be requested by the client;

l    client_header_buffer_size is used to specify the size of the headerbuffer from the client request header. For most requests, the buffer size of 1K is enough. If the message header is customized or there is a larger Cookie, the buffer size can be increased. It is set to 32K here;

l    large_client_header_buffers is used to specify the maximum number and size of caches for larger message headers in client requests, "4" is the number, "128K" is the size, and the maximum cache size is 4 128K;

l    The sendfile parameter is used to turn on efficient file transfer mode. tcp_nopush and TCP_ The two nodelay instructions are set to on to prevent network blocking;

l    keepalive_timeout sets the timeout for the client connection to remain active. After this time, the server will close the connection;

l    client_header_timeout sets the timeout for client request header reading. If the client does not send any data after this time, Nginx will return a "Request time out (408)" error;

l    client_body_timeout sets the client request body read timeout. If the client does not send any data after this time, Nginx will return "Request time out (408)" error, and the default value is 60;

send_timeout specifies the timeout for the response client. This timeout is limited to the time between two connection activities. If this time is exceeded, the client has no activity, and Nginx will close the connection.

three point three   HttpGzip module configuration

This module supports online real-time compression of output data streams. ​​​​​​​

gzip on;gzip_min_length 1k;gzip_buffers 4 16k;gzip_http_version 1.1;gzip_comp_level 2;gzip_types text/plain application/x-javascript text/css application/xml;gzip_vary on;

·         Gzip is used to turn on or off the gzip module, "gzip on" means to turn on gzip compression and compress the output data stream in real time;

·         gzip_min_length sets the minimum number of bytes of a page that can be compressed. The number of page bytes is obtained from the content length of the header header. The default value is 0, no matter how many pages are compressed. It is recommended to set the number of bytes greater than 1K. If it is less than 1K, the pressure may increase;

·         gzip_buffers means that four 16K memory units are applied as the compression result stream cache. The default value is to apply the same memory space as the original data size to store gzip compression results;

·         gzip_http_version is used to set and identify the HTTP protocol version. The default is 1.1. At present, most browsers already support GZIP decompression. Use the default;

·         gzip_comp_level is used to specify the GZIP compression ratio. 1 has the smallest compression ratio and the fastest processing speed; 9. The compression ratio is the largest, the transmission speed is fast, but the processing is the slowest, and it also consumes cpu resources;

·         gzip_types is used to specify the compression type. No matter whether it is specified or not, the "text/html" type will always be compressed;

·         GZIP_ The variable option allows the front-end cache server to cache GZIP compressed pages, such as Squid to cache Nginx compressed data.

three point four   Load balancing configuration

upstream{ip_hash;server;server down;server max_fails=3 fail_timeout=20s;server;}

Upstream is the HTTP Upstream module of Nginx. This module realizes load balancing from client IP to back-end server through a simple scheduling algorithm.
In the above setting, the name of a load balancer is specified through the upstream instruction. This name can be specified arbitrarily and can be called directly where needed later.

The load balancing module of Nginx currently supports four scheduling algorithms, which are introduced below. The latter two belong to the third-party scheduling methods.

·         Polling (default): each request is allocated to different back-end servers one by one in chronological order. If one of the back-end servers goes down, the faulty system will be automatically eliminated so that user access will not be affected;

·         Weight: Specifies the polling weight. The greater the weight value, the higher the access probability assigned. It is mainly used when the performance of each server at the back end is uneven;

·         ip_hash: each request is allocated according to the hash result of the access IP, so that visitors from the same IP can access a back-end server, which effectively solves the problem of session sharing in dynamic web pages;

·         Fair: a more intelligent load balancing algorithm than the above two. This algorithm can intelligently balance the load according to the page size and loading time, that is, allocate requests according to the response time of the back-end server, and give priority to those with short response time. Nginx itself does not support fair. If you need to use this scheduling algorithm, you must download nginx's upstream_fair module;

·         url_hash: allocate the request according to the hash result of the access URL, so that each URL is directed to the same back-end server, which can further improve the efficiency of the back-end cache server. Nginx itself does not support URLs_ If you need to use this scheduling algorithm, you must install the hash package of nginx.

In the HTTP Upstream module, you can specify the IP address and port of the back-end server through the server instruction, and set the status of each back-end server in load balancing scheduling. Common statuses are:

·         down: indicates that the current server does not participate in load balancing temporarily;

·         Backup: reserved backup machine. When all other non backup machines fail or are busy, the backup machine will be requested, so the pressure on this machine is the least;

·         max_ Failures: the number of times a request is allowed to fail. The default value is 1. When the maximum number of times is exceeded, proxy is returned_ next_ Error in upstream module definition;

·         fail_timeout: after experiencing max_ The time the service is suspended after failures. max_ Failures can be compared with fail_ Use with timeout.

Note that when the load scheduling algorithm is IP_ During hash, the state of the back-end server in load balancing scheduling cannot be weight and backup.

3.5 server virtual host configuration

It is recommended to write the content of virtual host configuration into another file and include it through the include instruction, which is more convenient for maintenance and management. ​​​​​​​

server{listen 80;server_name;index index.html index.htm index.php;root /wwwroot/www.cszhi.comcharset gb2312;access_log logs/ main;

The server flag defines the start of the virtual host, and listen is used to specify the service port of the virtual host, server_name is used to specify the IP address or domain name. Multiple domain names are separated by spaces. index is used to set the default home page address for access. The root instruction is used to specify the web page root directory of the virtual host. This directory can be a relative path or an absolute path. Charset is used to set the default encoding format of web pages. access_log is used to specify the storage path of the access log of this virtual host, and the last main is used to specify the output format of the access log.

three point six   location URL matching configuration

URL address matching is the most flexible part of Nginx configuration. Location supports regular expression matching and conditional matching. Users can filter dynamic and static web pages through the location instruction. Using location URL matching configuration, you can also implement reverse proxy for PHP dynamic parsing or load balancing.
The following settings are used to analyze and process web page URL s through the location command. All static files with extensions ending in. gif,. jpg,. jpeg,. png,. bmp and. swf are handed over to nginx for processing, and expires is used to specify the expiration time of static files, which is 30 days. ​​​​​​​

location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {root /wwwroot/;expires 30d;}

The following setting is to hand over all files under upload and html to nginx for processing. Of course, the upload and html directories are contained in the / web/wwwroot/ directory.

location ~ ^/(upload|html)/ {root /web/wwwroot/;expires 30d;}

In the last setting, location is the filtering processing of dynamic web pages under the virtual host, that is, all files with. jsp suffix are handed over to port 8080 of the local machine for processing. ​​​​​​​

location ~ .*.php$ {index index.php;proxy_pass http://localhost:8080;}

Posted by webweever on Wed, 29 Sep 2021 21:52:34 -0700