Calm down and talk about Nginx

Posted by TheJoey on Sun, 30 Jan 2022 06:36:24 +0100

Date: May 20, 2021
Author: Commas
Note: calm down and chat about Nginx, add tiles and bricks to your knowledge house, and hope to help you at the same time. If you think it's helpful, please give me a favor; If there is something wrong, I hope you guys will give me advice. Thank you ^ -^

1, Definition of Nginx

Nginx (engine x) is a high-performance HTTP and reverse proxy web server. It also provides IMAP/POP3/SMTP services. Nginx is rambler, the second most visited Russian by Igor sesoyev Ru site (Russian: Рамблер) The first public version 0.1.0 was released on October 4, 2004.

This paragraph is quoted from: Baidu Encyclopedia Nginx

2, Proxy mode of Nginx

proxy server: a springboard server between the requesting client and the original server. The forward proxy can hide the client and the reverse proxy can hide the original server.
Forward agent: the user knows the address of the target server, but cannot access it directly due to network restrictions and other reasons. At this time, you need to connect to the proxy server first, and then the proxy server can access the target server. The forwarding proxy target server does not know the real client.

1) Forward Proxy

Definition: the behavior of an intranet server to actively request the address or service of an extranet
Objects: clients
Direction: intranet → forwarding request → extranet

2) Reverse Proxy

Definition: the behavior of an external network to access an internal network service;
Objects: servers
Direction: external network → forwarding request → internal network

3) Load Balancer

Definition: Load Balancer is to distribute the load it bears to multiple operating units for execution according to certain rules and complete work tasks together, so that the server can withstand greater concurrent pressure.
Analogy: as if you break one chopstick and 10 chopsticks with the same force, one chopstick may not be able to withstand this force (load), but 10 chopsticks disperse that load, so you have the ability to resist you breaking them

(1) Polling
Each request is allocated to different back-end servers one by one in chronological order. If the back-end server goes down, it can be automatically eliminated.

upstream commas-server { 
       server 192.168.0.2; 
       server 192.168.0.5; 
       server 192.168.0.8; 
} 

(2) weight
Specify the weight proportion of each service. The weight is directly proportional to the access ratio. It is usually used for back-end services. The performance of machines is not uniform. Assign high weight to those with good performance to give full play to the maximum performance of the server

upstream commas-server { 
       server 192.168.0.2 weight=5; 
       server 192.168.0.5 weight=2; 
       server 192.168.0.8 weight=3; 
} 

( 3) ip_hash
Each request is allocated according to the hash result of access ip, so that each visitor can access a back-end server regularly, which can solve the problem of session.

upstream commas-server { 
       ip_hash; 
       server 192.168.0.2:88; 
       server 192.168.0.5:80; 
       server 192.168.0.8:80; 
} 

(4) minimum connection
Allocate the request to the service with the least number of connections.

upstream  commas-server {
       least_conn;
       server 192.168.0.2 weight=5; 
       server 192.168.0.5 weight=2; 
       server 192.168.0.8 weight=3; 
}

( 5)fair
Requests are allocated according to the response time of the back-end server, and those with short response time are allocated first.

upstream  commas-server {
       server 192.168.0.2 weight=5; 
       server 192.168.0.5 weight=2; 
       server 192.168.0.8 weight=3; 
       fair;   #Achieve priority allocation with short response time
}

( 6)url_hash
The request is allocated according to the hash result of the access url, so that each url is directed to the same back-end server, which is more effective when the back-end server is cache.

upstream commas-server {
    server squid1:3128;
    server squid2:3128;
    hash $request_uri;   #Each url is directed to the same back-end server
    hash_method crc32;
}

Knowledge gas station:
① In order to avoid unnecessary naming conflicts, it is better not to have underscores in the naming of variables, Because system variables use underscores_ Named;
② Each instruction must have a semicolon; It's over!

4) Separation of Dynamic And Static

Definition: distinguish between dynamic requests and static requests, and divert the dynamic and static requests to different servers, so as to improve the response speed of the website and reduce the burden of the server. (specify different suffixes through location to forward different requests, and the static resource cache time is configured by expires)

Implementation scheme 1: put static resources on a separate server (mainstream method)

Implementation scheme 2: dynamic files and static files are distributed together and separated by nginx configuration.

3, Download and installation of Nginx

This article takes Windows installation of Ningx as an example

1) Nginx Download

Baidu searches Nginx or directly enters the official website address, Nginx official website portal

It is recommended to install a Stable version, as shown in figure ②

Click "nginx/Windows-1.20.1" to download

2) Nginx installation

The downloaded installation package is a zip file. Just unzip it in the directory you want to install, as shown in the figure. The path I unzipped is D: \, that is, Nginx is installed in D:\nginx-1.20.1

The installed files are shown in the following figure:

3) Nginx directory

catalogueexplain
confConfiguration directory, all configuration files, where Nginx Conf is the main configuration file of the Nginx server.
contrib
docsdirectory
htmlStatic page directory
logsLog directory
tempTemporary file directory
nginx.exeNginx main program

4) Nginx test

Navigate to the current path and open cmd

View the current version of Nginx

Try to start Nginx, as shown in the figure below. The error reason why Nginx cannot run normally: the default configuration of Nginx is port 80, and port 80 of my computer has been occupied, so Nginx cannot start.

Change the default 80 port to 8080 port

Run Nginx again and enter the web address in the browser http://localhost:8080/ , access succeeded ^ -^
Welcome to nginx!

5) Nginx command

Use help to query command information, as shown below:

Summary of common commands

effectcommand
Start Nginxnginx
Exit nginx (graceful close)nginx -s quit
Stop nginx (quick stop)nginx -s stop
Hot restart nginx (reload profile)nginx -s reload
View Nginx versionnginx -v
Check the Nginx configuration filenginx -t
Forcibly shut down all Nginx processestaskkill /f /im nginx.exe

Knowledge gas station: s in nginx -s xxx is the abbreviation of signal;

4, Nginx profile

Configuration directory: D:\nginx-1.20.1\conf
Configuration file: nginx conf
Special note: each instruction must be written in; end

1) Structure of configuration file

1-1) schematic diagram of configuration file structure

1-2) description of configuration file structure

nameexplain
Global blockConfigure 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.
events blockThe 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 it is allowed to accept multiple network connections at the same time, and start the serialization of multiple network connections.
http blockAt the protocol level, you can nest multiple server s, configure most functions such as proxy, cache, log definition and the configuration of 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.
server blockAt the server level, configure the relevant parameters of the virtual host. There can be multiple servers in one http.
location blockRequest level, configure the routing of requests, and the processing of various pages.

2) Discussion on configuration file

2-1) configuration example of default configuration

# Note: each instruction must end with a semicolon^-^

#(1) Global block
#Run user
#user  nobody;
#worker_ The larger the processes, the more concurrent processing can be supported, which is usually set equal to the number of CPUs;
worker_processes  1;

#(2) events block
events {
	#Maximum number of concurrent links for a single background worker process
    worker_connections  1024;
}

#(3) http block
http {
	# (3-1) http global block
	# http global block configuration instructions include file import, MIME-TYPE definition, log customization, connection timeout, number of single link requests, etc;
    include       mime.types;
    default_type  application/octet-stream;

	#The sendfile instruction specifies whether nginx calls the sendfile function (zero copy mode) to output files. For ordinary applications, it is generally set to on. If it is used for downloading and other application disk IO heavy load applications, it can be set to off to balance the processing speed of disk and network I/O and reduce the uptime of the system
    sendfile        on;

	#Connection timeout
    keepalive_timeout  65;

	#(3-1-1) server block
	# The server block is closely related to the virtual host. From the user's point of view, the virtual host is exactly the same as an independent hardware host,
	# This technology is produced to save the hardware cost of Internet server;
	# ① Each http block can include multiple server blocks, and each server block is equivalent to a virtual host;
	# ② Each server block is also divided into global server blocks, and can contain multiple location blocks at the same time;
    server {
        listen       8080;		# The listening port is 8080
        server_name  localhost;	# Listen for IP address or domain name

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

		#(3-1-1-1-1) location block
        location / {
            root   html;
            index  index.html index.htm;
        }
		
		# Define error prompt page
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

2-2) configuration example of reverse proxy

# Note: each instruction must end with a semicolon^-^

#(1) Global block
#Run user
#user  nobody;
#worker_ The larger the processes, the more concurrent processing can be supported, which is usually set equal to the number of CPUs;
worker_processes  1;

#(2) events block
events {
	#Maximum number of concurrent links for a single background worker process
    worker_connections  1024;
}

#(3) http block
http {
	# (3-1) http global block
	# http global block configuration instructions include file import, MIME-TYPE definition, log customization, connection timeout, number of single link requests, etc;
    include       mime.types;
    default_type  application/octet-stream;

	#The sendfile instruction specifies whether nginx calls the sendfile function (zero copy mode) to output files. For ordinary applications, it is generally set to on. If it is used for downloading and other application disk IO heavy load applications, it can be set to off to balance the processing speed of disk and network I/O and reduce the uptime of the system
    sendfile        on;

	#Connection timeout
    keepalive_timeout  65;

	#(3-1-1) server block
	# The server block is closely related to the virtual host. From the user's point of view, the virtual host is exactly the same as an independent hardware host,
	# This technology is produced to save the hardware cost of Internet server;
	# ① Each http block can include multiple server blocks, and each server block is equivalent to a virtual host;
	# ② Each server block is also divided into global server blocks, and can contain multiple location blocks at the same time;
    server {
        listen       8080;		# The listening port is 8080
        server_name  localhost;	# Listen for IP address or domain name

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

		#(3-1-1-1-1) location block
        location / {
            # root   html;
            # index  index.html index.htm;
			# Note the above two lines of instructions to configure the reverse proxy
			# location interception, reverse proxy http://127.0.0.1:9090 handle
            proxy_pass http://127.0.0.1:9090;
        }
		
		# Define error prompt page
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

2-3) configuration example of load balancing

# Note: each instruction must end with a semicolon^-^

#(1) Global block
#Run user
#user  nobody;
#worker_ The larger the processes, the more concurrent processing can be supported, which is usually set equal to the number of CPUs;
worker_processes  1;

#(2) events block
events {
	#Maximum number of concurrent links for a single background worker process
    worker_connections  1024;
}

#(3) http block
http {
	# (3-1) http global block
	# http global block configuration instructions include file import, MIME-TYPE definition, log customization, connection timeout, number of single link requests, etc;
    include       mime.types;
    default_type  application/octet-stream;

	#The sendfile instruction specifies whether nginx calls the sendfile function (zero copy mode) to output files. For ordinary applications, it is generally set to on. If it is used for downloading and other application disk IO heavy load applications, it can be set to off to balance the processing speed of disk and network I/O and reduce the uptime of the system
    sendfile        on;

	#Connection timeout
    keepalive_timeout  65;
	
	upstream commas-server { 
		   server 192.168.0.2 weight=5; 
		   server 192.168.0.5 weight=2; 
		   server 192.168.0.8 weight=3; 
	} 
	
	#(3-1-1) server block
	# The server block is closely related to the virtual host. From the user's point of view, the virtual host is exactly the same as an independent hardware host,
	# This technology is produced to save the hardware cost of Internet server;
	# ① Each http block can include multiple server blocks, and each server block is equivalent to a virtual host;
	# ② Each server block is also divided into global server blocks, and can contain multiple location blocks at the same time;
    server {
        listen       8080;		# The listening port is 8080
        server_name  localhost;	# Listen for IP address or domain name

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

		#(3-1-1-1-1) location block
        location / {
            # root   html;
            # index  index.html index.htm;
			# Note the above two lines of instructions to configure reverse proxy and load balancing
            # Commas server is just a variable name, which can be named by itself
            proxy_pass http://commas-server;
        }
		
		# Define error prompt page
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

2-4) configuration example of dynamic and static separation

# Note: each instruction must end with a semicolon^-^

#(1) Global block
#Run user
#user  nobody;
#worker_ The larger the processes, the more concurrent processing can be supported, which is usually set equal to the number of CPUs;
worker_processes  1;

#(2) events block
events {
	#Maximum number of concurrent links for a single background worker process
    worker_connections  1024;
}

#(3) http block
http {
	# (3-1) http global block
	# http global block configuration instructions include file import, MIME-TYPE definition, log customization, connection timeout, number of single link requests, etc;
    include       mime.types;
    default_type  application/octet-stream;

	#The sendfile instruction specifies whether nginx calls the sendfile function (zero copy mode) to output files. For ordinary applications, it is generally set to on. If it is used for downloading and other application disk IO heavy load applications, it can be set to off to balance the processing speed of disk and network I/O and reduce the uptime of the system
    sendfile        on;

	#Connection timeout
    keepalive_timeout  65;

	#(3-1-1) server block
	# The server block is closely related to the virtual host. From the user's point of view, the virtual host is exactly the same as an independent hardware host,
	# This technology is produced to save the hardware cost of Internet server;
	# ① Each http block can include multiple server blocks, and each server block is equivalent to a virtual host;
	# ② Each server block is also divided into global server blocks, and can contain multiple location blocks at the same time;
    server {
        listen       8080;		# The listening port is 8080
        server_name  localhost;	# Listen for IP address or domain name

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

		#(3-1-1-1-1) location block = = = "dynamic resource request"
        location / {
            root   html;
            index  index.html index.htm;
        }
        
		#(3-1-1-1-2) location block = = = "static state resource request"
	 	location ~ .*\.(gif|jpg|jpeg|bmp|png|ico|txt|js|css)$ { 
	 		# The static resources of this example are obtained locally;
	 		# Static resources can also be obtained from the static resource server through reverse proxy;
            Root / data /; 
            Expires 3D; # cache for 3 days 
        } 
		
		# Define error prompt page
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

3) Discussion on location block

location matching syntax rule: location [^ ~ | = | ~ | ~ * |! ~ | ~ * | @] pattern {...}
Among them, pattern determines whether it is a url or a regular expression according to the previous modifier

3-1) syntax description of location

Modifier explainExamples
nothingStart of matching urllocation /abc {......}
^~Similar, no modifier, but higher prioritylocation ^~ /abc {......}
=Exact match urllocation = /abc {......}
~Case sensitive regular matchinglocation ~ ^/abc$ {......}
~*Case insensitive regular matchinglocation ~* ^/abc$ {......}
!~Case sensitive regular mismatchlocation ~ ^/abc$ {......}
!~*Case insensitive regular mismatchlocation ~* ^/abc$ {......}
@Define a named location for internal redirectionlocation @abc {......}

In particular, let's talk about the usage of the @ modifier. The internal redirection of Nginx is as follows:

#Internal redirection @ bbb
	location /aaa {
    	try_files index.html @bbb;
	}

#Define a @ bbb
	location @bbb {
		bbb.html
    }

Knowledge gas station: try_files is HTTP in nginx_ The instructions carried by the core module can mainly replace some rewrite instructions to improve the parsing efficiency.
Official website: http://nginx.org/en/docs/http/ngx_http_core_module.html#try_files

3-2) search order and priority in location

When there are multiple location instructions, Nginx has a set of priority rules, which are roughly summarized as follows:

First accurate, then conditional prefix, three and regular,
Four, unconditional, who at the same level listens to who before
priorityruleExamples
Exact matchlocation = /abc {......}
^~(conditional) prefix matchlocation ^~ /abc {......}
Regular matchinglocation ~ ^/abc$ {......}
No modifier (unconditional) prefix matcheslocation /abc {......}

If the peer listens to the person in front of him, as shown below, visit / a123 and A12 will be returned HTML Oh!

	# first
	location ~ ^/a12 {
		a12.html;
	}
	
	# the second
	location ~ ^/a1 {
		a1.html;
	}

3-3) difference between root and alias

The main difference between root and alias is how Nginx interprets the URL behind location and maps the request to the server file in different ways, as shown below:

instructionsrootalias
grammarroot pathalias path
Default valueroot html- -
Configuration blockhttp,server,locationlocation
explainSet the local file root of the request URLReassign the matching access path as the newly defined file path
resultroot path + location pathalias path replaces location path
	# If request: / abc/a.html,
	# Then the web server will return the file of / www/root/html/abc/a.html on the server
	location ^~ /abc/ {
		root /www/root/html/;
	}
	
	# If request: / abc/a.html,
	# Then the web server will return the file of / www/root/html/a.html on the server
	location ^~ /abc/ {
		alias /www/root/html/;
	}

Knowledge service station: it is particularly worth pointing out that the alias must be used / ended after it, otherwise the file cannot be found
Reference article:
Nginx root instruction: root directory configuration
Nginx alias instruction: virtual directory configuration

Reference article:
1,Nginx Module ngx_http_core_module
2. Nginx Chinese document
3,Common configuration of nginx (reverse proxy, load balancing, dynamic static separation, high availability cluster)

Copyright notice: This article is the original article of the blogger. If you need to reprint it, please give:
Original link: https://blog.csdn.net/qq_35844043/article/details/117072364

Topics: Nginx location