Working principle and configuration of nginx

Keywords: Linux Operation & Maintenance Nginx server

Working principle and configuration of nginx

Module and working principle of nginx

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 URL 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

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

  • 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
  • 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

nginx module is divided into: core module, event module, standard Http module, optional Http module, mail module, third-party module and patch

  • 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
    • 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

How nginx works

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.

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

The following figure shows the basic WEB service request steps

Installation and configuration of nginx

nginx installation

Create system user nginx

[root@localhost ~]# useradd -r -M -s /sbin/nologin nginx

Installation dependent environment

[root@localhost ~]# yum -y install pcre-devel openssl openssl-devel gd-devel gcc gcc-c++
[root@localhost ~]# yum -y groups mark install 'Development Tools'
Last metadata expiration check: 2:59:11 Before, it was executed at 01:04:32 on Monday, October 25, 2021.
Dependency resolution.
 software package       framework        edition            Warehouse          size
Installation group:
 Development Tools

Transaction summary


Create log storage directory

[root@localhost ~]# mkdir -p /var/log/nginx
[root@localhost ~]# chown -R nginx.nginx /var/log/nginx

Download nginx

[root@localhost ~]# cd /usr/src/
[root@localhost src]# wget
--2021-10-25 04:06:16--
 Resolving host ( 

Compile and install

[root@localhost src]# ls
debug  kernels  nginx-1.12.0.tar.gz
[root@localhost src]# tar xf nginx-1.12.0.tar.gz
[root@localhost src]# cd nginx-1.12.0
[root@localhost nginx-1.12.0]# ./configure \
--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 \

[root@localhost nginx-1.12.0]# make -j $(grep 'processor' /proc/cpuinfo | wc -l) && make install

nginx configuration

Service control mode, using nginx command

Configure environment variables

[root@localhost ~]# echo 'export PATH=/usr/local/nginx/sbin:$PATH' > /etc/profile.d/
[root@localhost ~]# . /etc/profile.d/

Service control mode, using nginx command

-t check the configuration file syntax

[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

-v output the version of nginx

[root@localhost ~]# nginx -v
nginx version: nginx/1.20.1

-c specify the path of the configuration file

[root@localhost ~]# nginx -s stop ; nginx -c /opt/nginx.conf  ##Directly stop and start
[root@localhost ~]# ps -ef|grep nginx
root       99290       1  0 03:32 ?        00:00:00 nginx: master process nginx -c /opt/nginx.conf
nginx      99291   99290  0 03:32 ?        00:00:00 nginx: worker process
nginx      99292   99290  0 03:32 ?        00:00:00 nginx: worker process
root      101138    1653  0 03:33 pts/0    00:00:00 grep --color=auto nginx

-s sends a service control signal. The optional values are {stop | quit | reopen}

[root@localhost ~]# nginx -s quit
[root@localhost ~]# ss -antl
State  Recv-Q Send-Q  Local Address:Port   Peer Address:Port Process                                                      
LISTEN 0      128 *                                                                 
LISTEN 0      128              [::]:22             [::]:*                                                      

Detailed explanation of nginx configuration file

Main configuration file: / usr/local/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
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

Sample Nginx configuration file

[root@localhost ~]# vim /usr/local/nginx/conf
# Global block
 user www-data;  ##user
 worker_processes  2;  ## The default is 1. It is generally recommended to set the number of CPU cores to 1-2 times
 error_log  logs/error.log; ## Error log path
 pid  logs/; ## Process id
 # Events block
 events {
   # Use epoll's I/O model to handle polling events.
   # It can not be set. nginx will select the appropriate model according to the operating system
   use epoll;
   # The maximum number of connections for the worker process. 1024 by default
   worker_connections  2048;
   # Keep alive timeout at http level
   keepalive_timeout 60;
   # Buffer size of the client request header
   client_header_buffer_size 2k;
 # http block
 http { 
   include mime.types;  # Import file extension and file type mapping table
   default_type application/octet-stream;  # Default file type
   # Log format and access log path
   log_format   main '$remote_addr - $remote_user [$time_local]  $status '
     '"$request" $body_bytes_sent "$http_referer" '
     '"$http_user_agent" "$http_x_forwarded_for"';
   access_log   logs/access.log  main; 
   # sendfile mode is allowed to transfer files. The default value is off.
   sendfile     on;
   tcp_nopush   on; # Only when sendfile is on.
   # http server block
   # Simple reverse proxy
   server {
     listen       80;
     access_log   logs/domain2.access.log  main;
     # Forward dynamic request to web application server
     location / {
       deny;  # Rejected ip
       allow; # Allowed ip   
     # Error page
     error_page   500 502 503 504  /50x.html;
         location = /50x.html {
             root   html;
   # load balancing 
   upstream backend_server {
     server weight=5; # The higher the weight, the greater the weight
     server weight=1;
     server backup; # Hot standby
   server {
     listen          80;
     access_log      logs/big.server.access.log main;
     charset utf-8;
     client_max_body_size 10M; # Limit the file size uploaded by the user. The default is 1M
     location / {
       # Using proxy_pass forwards the request to a set of application servers defined through upstream
       proxy_pass      http://backend_server;
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
       proxy_set_header Host $http_host;
       proxy_redirect off;
       proxy_set_header X-Real-IP  $remote_addr;

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

derective value1 [value2 ...];

Supported variables:

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

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

Posted by ChrisMayhew on Mon, 25 Oct 2021 01:59:12 -0700