Detailed explanation of nginx - working principle and configuration file

Posted by jakebrewer1 on Tue, 26 Oct 2021 03:28:41 +0200

How nginx works

Nginx consists of kernel and modules. Among them, the design of the kernel is very small and concise, and the work completed is also very simple. Only by looking up the configuration file, the client request is mapped to a location block (location is an instruction in nginx configuration for URI matching), and each instruction configured in this location will start different modules to complete the corresponding work.

Module classification of nginx

The module of nginx is divided into core module, basic module and third-party module

  • HTTP module, EVENT module and MAIL module are core modules
  • HTTP Access module, HTTP FastCGI module, HTTP Proxy module and HTTP Rewrite module are basic modules
  • HTTP Upstream module, Request Hash module, Notice module and HTTP Access Key module belong to third-party modules
    Modules developed by users according to their own needs belong to third-party modules. It is with the support of so many modules that the function of nginx will be so powerful

Then download the nginx installation package. After decompression, enter the configure directory under the decompression directory, view the help documents, and view the core modules and basic modules

[root@localhost nginx-1.20.1]# ./configure --help
.......
--with-http_ssl_module             enable ngx_http_ssl_module
  --with-http_v2_module              enable ngx_http_v2_module
  --with-http_realip_module          enable ngx_http_realip_module
  --with-http_addition_module        enable ngx_http_addition_module
  --with-http_xslt_module            enable ngx_http_xslt_module
  --with-http_xslt_module=dynamic    enable dynamic ngx_http_xslt_module
  --with-http_image_filter_module    enable ngx_http_image_filter_module
........
//If the word with is included, the function will not be added during compilation. If you want to use this function, add the required parameters during compilation

......
--without-http_charset_module      disable ngx_http_charset_module
  --without-http_gzip_module         disable ngx_http_gzip_module
  --without-http_ssi_module          disable ngx_http_ssi_module
  --without-http_userid_module       disable ngx_http_userid_module
  --without-http_access_module       disable ngx_http_access_module
  --without-http_auth_basic_module   disable ngx_http_auth_basic_module
  --without-http_mirror_module       disable ngx_http_mirror_module
......
//If the word without is included, this function is provided by default during compilation. If you do not want to use this function, you can add the required parameters during compilation

nginx modules are divided into three types in terms of function:

  • Proxies (agent module). It is the HTTP Upstream module of nginx. These modules mainly interact with some back-end services, such as fastcgi, to realize the functions of service proxy and load balancing
  • Handlers. This kind of module directly processes the request, outputs the content and modifies the header information. Generally, there can only be one handler module
  • Filters. This kind of module is mainly used to modify the output of other processor modules, and finally output by nginx

Nginx basic modules: the so-called basic modules refer to the default function modules of nginx. The instructions provided by them allow you to use variables that define the basic functions of nginx. They cannot be disabled during compilation, including:

  • Core module: basic functions and instructions, such as process management and security. Most of the common core module instructions are placed at the top of the configuration file (at the beginning of each line, the top of the official document is called main)
  • Event module: the ability to configure network usage in Nginx. Most of the common events module instructions are placed at the top of the configuration file
  • Configuration module: provides an inclusion mechanism

For specific instructions, please refer to nginx Official documents

Click the official document link to see a sample configuration file and how to use the instructions

Detailed explanation of nginx working principle

Nginx modules are directly compiled into nginx, so they belong to static compilation.

After starting nginx, the module of nginx is loaded automatically. Unlike Apache, first compile the module into a so file, and then specify whether to load it in the configuration file.

When parsing the configuration file, each module of nginx may process a request, but the same processing request can only be completed by one module.

Process architecture of nginx:

  • When nginx is started, a Master process will be started. This process does not process any client requests. It is mainly used to generate worker threads. A worker thread is used to process n requests. (it is a worker thread by default, and the number of workers can be modified in the configuration file)
[root@localhost conf]# vim nginx.conf
#user  nobody;
worker_processes  1;     //Here is the number of worker processes, which can be set according to your own needs

//The default number of worker s is only one at this time
[root@localhost ~]# ps -ef |grep nginx
root       33402       1  0 10:32 ?        00:00:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx      33403   33402  0 10:32 ?        00:00:00 nginx: worker process
root       34091   34068  0 18:45 pts/1    00:00:00 grep --color=auto nginx

//Number of worker processes modified
[root@localhost conf]# vim nginx.conf
#user  nobody;
worker_processes  4;     //Change to 4

[root@localhost ~]# nginx -s reload / / reload after modifying the configuration file
[root@localhost ~]# ps -ef |grep nginx
root       33402       1  0 10:32 ?        00:00:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx      34095   33402  0 18:50 ?        00:00:00 nginx: worker process
nginx      34096   33402  0 18:50 ?        00:00:00 nginx: worker process
nginx      34097   33402  0 18:50 ?        00:00:00 nginx: worker process
nginx      34098   33402  0 18:50 ?        00:00:00 nginx: worker process
root       34100   34068  0 18:50 pts/1    00:00:00 grep --color=auto nginx


The following figure shows a routine HTTP request and response process of nginx module

The following figure shows the basic WEB service request steps:

1. Establish a connection (visit the domain name and find the website port 80)
2. Accept the request (local apache or nginx80 port number accepts the request)
3. Processing requests
4. Access resources (local resource search or RS search)
5. Build response (encapsulate response message)
6. Send response (sent to client through network protocol)
7. Record the transaction process (log, record the whole transaction process)

nginx post installation configuration

nginx deployment click here

  • nginx command parameters
//Service control mode, using nginx command
    -t  //Check configuration file syntax
    -v  //Output the version of nginx
    -V  //View the parameters selected at compile time
    -c  //Specifies the path to the configuration file
    -s  //Send the service control signal. The optional values are {stop | quit | reopen}
  • Test parameter - t
[root@localhost ~]# nginx -t 
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
//At this time, the configuration file has not been modified and the syntax is correct. We think to modify the configuration file and test the syntax error

[root@localhost conf]# vim nginx.conf
#user  nobody;
worker_processes  4   //Put here; Remove
[root@localhost ~]# nginx -t 
nginx: [emerg] directive "worker_processes" is not terminated by ";" in /usr/local/nginx/conf/nginx.conf:12
nginx: configuration file /usr/local/nginx/conf/nginx.conf test failed
//At this time, syntax errors will be checked. It should be noted that even if the syntax of the configuration file is correct, it does not mean that the configuration file is OK
  • Test parameters - V, - V
[root@localhost ~]# nginx -v 
nginx version: nginx/1.20.1
//In addition to - V, there are - V, - V to view the parameters used during compilation. If you need to recompile, if you need to add or reduce parameters, this project is very important

[root@localhost ~]# nginx -V
nginx version: nginx/1.20.1
built by gcc 8.5.0 20210514 (Red Hat 8.5.0-3) (GCC) 
built with OpenSSL 1.1.1k  FIPS 25 Mar 2021
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log
  • Test parameter - s
nginx -s Common options stop,reload
  • Test parameter - c
//When nginx starts, the default configuration file is / conf/nginx.conf in the installation directory. However, when the configuration file needs to be modified in the production environment, in order to avoid errors and affect the user experience, you can temporarily copy a copy of the configuration file to another directory and then modify it
//Because the configuration file contains contains, when copying the configuration file, the included file is also copied
[root@localhost conf]# cp nginx.conf mime.types /opt/
[root@localhost opt]# ls 
mime.types  nginx.conf

//Take the number of worker processes modified as an example, use the following parameter - c
[root@localhost opt]# vim nginx.conf / / modifies the copied configuration file
#user  nobody;
worker_processes  5;    //Change to 5
.......

//Use the configuration file under / opt to take effect. When stopping nginx and reassigning the configuration file, in order not to affect the user experience, use the command on one line and in the middle; separate
[root@localhost ~]# nginx -s stop;nginx -c /opt/nginx.conf 
[root@localhost ~]# ps -ef|grep nginx
root        1345       1  0 09:45 ?        00:00:00 nginx: master process nginx -c /opt/nginx.conf
nginx       1347    1345  0 09:45 ?        00:00:00 nginx: worker process
nginx       1348    1345  0 09:45 ?        00:00:00 nginx: worker process
nginx       1349    1345  0 09:45 ?        00:00:00 nginx: worker process
nginx       1350    1345  0 09:45 ?        00:00:00 nginx: worker process
nginx       1351    1345  0 09:45 ?        00:00:00 nginx: worker process
root        1353    1316  0 09:45 pts/1    00:00:00 grep --color=auto nginx

//If an error occurs when the copied configuration file is modified, it can be restored to the original configuration file immediately
[root@localhost ~]# nginx -s stop;nginx

Detailed explanation of nginx configuration file

Main configuration file: under the installation path, / conf/nginx.conf

  • When nginx is started by default, the configuration file used is the installation path / conf/nginx.conf file
  • You can specify the configuration file to read with the - c option when you start nginx

Common configuration files of nginx and their functions

configuration fileeffect
nginx.confBasic configuration file of nginx (often used)
mime.typesExtension files associated with MIME types
fastcgi.conffastcgi related configurations
proxy.confproxy related configuration
sites.confConfigure the websites provided by nginx, including virtual hosts

Detailed explanation of nginx.conf configuration

The content of nginx.conf is divided into the following paragraphs:

  • Mainconfiguration segment: global configuration segment. The main configuration section may contain the event configuration section
  • Event {}: define the working characteristics of the event model
  • http {}: defines the configuration related to the http protocol

Configuration instruction: to end with a semicolon, the syntax format is as follows:

derective(instructions)  value1 [value2 ...];

Supported variables:

  • Built in variable: the module will provide built-in variable definitions
  • Custom variable: set var_name value (infrequently used)

Configuration parameters for debugging and locating problems

daemon {on|off};    //Whether to run nginx as a daemon. It should be set to off during debugging
master_process {on|off};    //Whether to run nginx in the master/worker model. It can be set to off during debugging
error_log Location level;    //Configure error log (common)

error_ The position and level in the log can have the following options:

positionlevel
file (common)
stderr
syslog:server=address[,parameter=value]
memory:size
Debug: to use the debug level, you need to use the – with debug option when compiling nginx
info
notice
warn
Error (common)
crit
alert
emerg
The level increases from high to bottom. The lower the level, the more detailed the record

Topics: Operation & Maintenance Nginx server