Nginx theory + examples explained in detail

1. Introduction to nginx

  • Nginx is a lightweight web server/reverse proxy server and email (IMAP/POP3) proxy server.
  • Nginx was developed by Russian programmer lgor Sysoev and was originally used by Rambler, a large Russian portal and search engine.
  • The first public version 0.1.0 was released on October 4, 2004. It releases its source code under a BSD-like license and is known for its stability, rich feature set, sample configuration files, and low system resource consumption. On June 1, 2011, nginx 1.0.4 was released.
  • The characteristics of nginx are that it occupies less memory and has strong concurrency capabilities. In fact, nginx’s concurrency capabilities do perform better among web servers of the same type. Users of nginx websites in mainland China include: Baidu, JD.com, Sina, NetEase, Tencent, Taobao, etc. .

2. Characteristics and advantages of nginx.

1. nginx features

Nginx is a very high-performance WEB and reverse proxy server. It has many very superior features:
(1) In the case of high connection concurrency, nginx is a good substitute for the apache server and can support up to 50,000 concurrent connections. The corresponding number
(2) Use epoll and kqueue as the development model
(3) Nginx as a load balancing server: nginx can directly support external services with PHP programs internally, and can also support external services as an HTTP proxy server
(4) Nginx is written in C, and its system resource overhead and CPU usage efficiency are much better than Perlbal.

2. Advantages of nginx

(1) High concurrent connections: The official test can support 50,000 concurrent connections, and in the actual production environment, the number of concurrent connections reaches 20,000-30,000. (
2) Low memory consumption: 10 nginx processes are opened under 30,000 concurrent connections. It only consumes 150M of memory (15M*10=150M)
(3) The configuration file is very simple: the style is as easy to understand as the program
(4) Low cost: nginx is an open source software and can be used for free. Purchasing hardware load balancing switches such as F5 BIG-IP and NetScaler requires more than 100,000 to hundreds of thousands of yuan
(5) Supports Rewrite rewriting rules: it can allocate HTTP requests to different back-end servers based on different domain names and URLs. Group
(6) Built-in health check function: If a web server in the backend of Nginx Proxy goes down, front-end access will not be affected
(7) Bandwidth saving: GZIP compression is supported, and the header header of the browser's local cache can be added
(8 ) High stability: used for reverse proxy, the probability of downtime is minimal
(9) Modular design: modules can be compiled dynamically
(10) Good peripheral support: complete documentation, secondary development and more modules (11) Support hot deployment : Can reload configuration files without downtime
(12) Supports event-driven, AlO (Asynclo, asynchronous l0), mmap (Memory Map, memory mapping) and other performance optimizations

3. Functions and application categories of nginx

1. Basic functions of nginx

(1) Web server for static resources, capable of caching open file descriptors
(2) Reverse proxy server for http, smtp, pop3 protocols
(3) Cache acceleration, load balancing
(4) Support FastcGl (fpm, LNMP), uwSGl (Python), etc.
(5) Modularization (non-DSo mechanism), filter zip, SSI and image resizing
(6) Support SSL

2. Extended functions of nginx

(1) Virtual host based on name and IP
(2) Supports keepalive
(3) Supports smooth upgrade
(4) Customizes access logs and supports using log buffer to improve log storage performance
(5) Supports URL rewriting
(6) Supports path aliases
(7) Support I- and user-based access control
(8) Support rate limit and concurrency limit

3. Application categories of nginx

(1) Use nginx combined with FastcGl to run PHP, JSP, Perl and other programs
(2) Use nginx_ for reverse proxy, load balancing, rule filtering
(3) Use nginx to run static HTML web pages and pictures
(4) nginx and other new technologies combined application

4. Modules and working principles of nginx

  • nginx consists of kernel and modules. Among them, the design of the kernel is very small and concise, and the work done is also very simple. It only maps the client request to a location block by looking up the configuration file (location is a directive in the nginx configuration, used for URL matching), and in this Each command configured in location will start a different module to complete the corresponding work.

1. Module classification of nginx

nginx modules are structurally divided into core modules, basic modules and third-party modules

(1) HTTP module, EVENT module and MAIL module are core modules

(2) HTTP Access module, HTTP FastCGl, module, HTTP Proxy module and HTTP Rewrite module are basic modules

(3) HTTP Upstream module, Request Hash module, Notice module and HTTP Access Key module are third-party modules

  • Modules developed by users according to their own needs are third-party modules. It is precisely with the support of so many modules that the functions of nginx. can be so powerful.

nginx modules are functionally divided into three categories, namely:

(1)Handlers (processor module). This type of module directly processes requests and performs operations such as outputting content and modifying header information. Generally, there can only be one handlers processor module.

(2)Filters (filter module). This type of module mainly modifies the content output by other processor modules, and is finally output by nginx.

(3) Proxies (agent module). It is modules such as nginx's HTTP Upstream. These modules mainly interact with some back-end services such as fastcgi and other operations to implement functions such as service proxy and load balancing.

The nginx module is divided into: core module, event module, standard HTTP module, optional HTTP module, email module, third-party modules and patches, etc.

nginx, basic module: The so-called basic module refers to the default function module of nginx. The instructions they provide allow you to use variables that define the basic functions of nginx and cannot be disabled during compilation, including:

(1) Core module: basic functions and instructions, such as process management and security. Most of the common core module directives are placed at the top of the configuration file

(2) Event module: The ability to configure network usage within Nginx. Common events module directives, =most are placed at the top of the configuration file

(3) Configuration module: Provides inclusion mechanism

2. How nginx works

  • The modules of nginx. are compiled directly into nginx, so they are static compilation methods.
  • After starting nginx, the nginx module is automatically loaded. Unlike Apache, the module is first compiled into an so file, and then whether to load is specified in the configuration file.
  • When parsing the configuration file, each module of nginx may process a certain request, but the same processing request can only be completed by one module.
    nginx process architecture:
  • 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. One worker thread is used to process n requests.

1. Nginx process model
Nginx adopts multi-process working mode by default. After Nginx is started, it will run a master process and multiple worker processes. The master acts as the interactive interface between the entire process group and the user, monitors the process at the same time, and manages the worker process to implement functions such as service restart, smooth upgrade, log file replacement, and configuration file taking effect in real time. Workers are used to handle basic network events. Workers are equal and they compete together to handle requests from clients.

Insert image description here

When creating the master process, first establish the socket (listenfd) that needs to be monitored, and then fork() multiple worker processes from the master process. In this way, each worker process can listen to the socket requested by the user. Generally speaking, when a connection comes in, all workers will receive a notification, but only one process can accept the connection request, and the others fail. This is the so-called thundering herd phenomenon. nginx provides an accept_mutex (mutex lock). With this lock, there will only be one process connecting in accpet at the same time, so there will be no panic problem.

First open the accept_mutex option. Only the process that has obtained accept_mutex will add the accept event. nginx. Use a variable called ngx_accept_disabled to control whether to compete for the accept_mutex lock. ngx_accept_disabled = ngin...the total number of all connections in a single process / 8 - the number of idle connections. When ngx_accept_disabled is greater than 0, no attempt will be made to acquire the accept_mutex lock. The larger the ngx_accept_disable is, the more opportunities there will be to give up, so that other processes can acquire the lock. The chances are greater. Without accepting, the number of connections in each worker process will be controlled, and the connection pools of other processes will be utilized. In this way, nginx controls the balance of connections among multiple processes.

Each worker process has an independent connection pool, and the size of the connection pool is worker_connections. What is saved in the connection pool here is not actually a real connection, it is just an array of ngx_connection_t structure of the size of worker_connections. Moreover, nginx will save all free ngx_connection_t through a linked list free_connections. Every time a connection is obtained, it will get one from the free connection list. After using it, it will be put back into the free connection list. The maximum number of connections that can be established by an nginx... should be worker_connections * worker_processes. Of course, what we are talking about here is the maximum number of connections. For HTTP requests to local resources, the maximum number of concurrencies that can be supported is worker_connections * worker_processes. If HTTP is used as a reverse proxy, the maximum number of concurrencies should be worker_connections * worker_processes/2 . Because as a reverse proxy server, each concurrent connection will establish a connection with the client and a connection with the back-end service, which will occupy two connections.

5. nginx source code installation

Environment preparation
: configure the mirror source and turn off the firewall

[root@localhost ~]# ls /etc/yum.repos.d/
CentOS-Base.repo   epel.repo                  epel-testing.repo
epel-modular.repo  epel-testing-modular.repo


创建系统用户
[root@localhost ~]# useradd -rMs /sbin/nologin nginx
[root@localhost ~]# id nginx 
uid=995(nginx) gid=992(nginx) groups=992(nginx)


安装开发工具包
[root@localhost ~]# yum -y groups mark install 'Development Tools'


创建日志存放路径
[root@localhost ~]# mkdir /var/log/nginx
[root@localhost ~]# chown -R nginx.nginx /var/log/nginx/
[root@localhost ~]# ll -d /var/log/nginx/
drwxr-xr-x. 2 nginx nginx 6 Oct 10 16:56 /var/log/nginx/

Install nginx

[root@localhost ~]# wget http://nginx.org/download/nginx-1.20.2.tar.gz
--2022-10-10 17:04:05--  http://nginx.org/download/nginx-1.20.2.tar.gz
Resolving nginx.org (nginx.org)... 3.125.197.172, 52.58.199.22, 2a05:d014:edb:5702::6, ...
Connecting to nginx.org (nginx.org)|3.125.197.172|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 1062124 (1.0M) [application/octet-stream]
Saving to: ‘nginx-1.20.2.tar.gz’

nginx-1.20.2.tar.gz 100%[=================>]   1.01M   229KB/s    in 6.9s    

2022-10-10 17:04:13 (150 KB/s) - ‘nginx-1.20.2.tar.gz’ saved [1062124/1062124]

[root@localhost ~]# ls
anaconda-ks.cfg  nginx-1.20.2.tar.gz
[root@localhost ~]# tar -zxf nginx-1.20.2.tar.gz -C /usr/src/

预编译
[root@localhost nginx-1.20.2]# cd /usr/local/nginx-1.20.2/
./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 \
--error-log-path=/var/log/nginx/error.log
[root@localhost nginx-1.20.2]# make
[root@localhost nginx-1.20.2]# make install

配置环境变量以便启动nginx
[root@localhost nginx-1.20.2]# echo 'export PATH=/usr/local/nginx/sbin:$PATH' > /etc/profile.d/nginx.sh
[root@localhost nginx-1.20.2]# . /etc/profile.d/nginx.sh 
[root@localhost nginx-1.20.2]# nginx
[root@localhost nginx-1.20.2]# ss -antl
State   Recv-Q  Send-Q     Local Address:Port     Peer Address:Port  Process  
LISTEN  0       128              0.0.0.0:22            0.0.0.0:*              
LISTEN  0       128              0.0.0.0:80            0.0.0.0:*              
LISTEN  0       128                 [::]:22               [::]:*    

//Start nginx and check the port status. Service control mode, use nginx command
-t to check the configuration file syntax
-v to output the nginx version
-c to specify the configuration file path
-s to send the service control signal. The optional values ​​are stop, auit, and reopen. , reload

6. Detailed explanation of configuration files

Main configuration file:/usr/local/nginx/nginx.conf.
When starting nginx by default, the configuration file used is: installation path/conf/nginx.conf.
You can specify the configuration file to be read through the -c option when starting nginx.
// Common configuration files of nginx and their functions
nginx.conf Basic configuration file of nginx
mime.types Extension file associated with MIME type
fastcgi.conf Configuration related to fastcgi
proxy.conf Configuration related to proxy
sites.conf Configuration nginx, provided website, including web hosting

7. Deploy lnmp organization

The following PHP-MySQL are all source code installations. You can refer to the MySQL installation I wrote before.

1. MySQL operation

[root@my ~]# ss -antl | grep 3306
LISTEN 0      80                 *:3306            *:*   

2. PHP side operation

PHP configuration
After successful deployment, configure the following content

[root@node1 php-fpm.d]# pwd
/usr/local/php7/etc/php-fpm.d
listen = 0.0.0.0:9000
listen.allowed_clients = 192.168.47.137
[root@node1 php-fpm.d]# ss -antl | grep 9000
LISTEN 0      128               0.0.0.0:9000      0.0.0.0:*  


网页测试目录
[root@node1 php-fpm.d]# mkdir /var/www/html -p
[root@node1 php-fpm.d]# cd /var/www/html/
[root@node1 html]# ls
[root@node1 html]# vim index.php
[root@node1 html]# useradd -Mrs /sbin/nologin nginx
[root@node1 html]# id nginx 
uid=975(nginx) gid=974(nginx) groups=974(nginx)
[root@node1 html]# chown -R nginx.nginx /var/www/html/
[root@node1 html]# ll
total 4
-rw-r--r-- 1 nginx nginx 21 Oct 11 19:02 index.php

3. nginx operation

[root@localhost conf]# cd /usr/local/nginx/conf
[root@localhost conf]# vim nginx.conf
location / {
            root    html;
            index  index.php index.html index.htm;
        }
   location ~ \.php$ {
            root           /var/www/html;
            fastcgi_pass   192.168.47.50:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  /var/www/html/$fastcgi_script_name;
            include        fastcgi_params;
        }


拿nginxip访问
[root@localhost conf]# ss -antl | grep 80
LISTEN 0      128          0.0.0.0:80        0.0.0.0:* 

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-3YrgFFHM-1666171360698)(./1665487107955.png)]

8. Smooth upgrade

//Steps for smooth upgrade
1. Obtain the previous compilation parameters
2. Download the new module
3. Recompile the software, add –add-module = decompression path of the new module
4. Stop the service and back up the original program
5. Use the source program New program coverage
6. Start new program

1. Based on previously deployed nginx

Make sure the webpage is accessible, just use your own mobile phone hotspot and other devices
[https://github.com/openresty/echo-nginx-module]

Download to local

[root@localhost ~]# wget https://github.com/openresty/echo-nginx-module
解压
[root@localhost ~]# unzip echo-nginx-module-master.zip 

2. Obtain the compilation parameters of previously installed nginx.
It is recommended to use the nginx-1.20.0 version of the nginx package here.

Check your original binary installed nginx module and copy it

[root@localhost ~]# nginx -V
nginx version: nginx/1.20.0
built by gcc 8.5.0 20210514 (Red Hat 8.5.0-4) (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


重新压缩一份nginx
[root@localhost ~]# tar -zxf nginx-1.20.0.tar.gz 


重新预编译软件
[root@localhost nginx-1.20.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 \
--error-log-path=/var/log/nginx/error.log \
--add-module=../echo-nginx-module-master

//添加成功
[root@localhost nginx-1.20.0]# make
sed -e "s|%%PREFIX%%|/usr/local/nginx|" \
	-e "s|%%PID_PATH%%|/usr/local/nginx/logs/nginx.pid|" \
	-e "s|%%CONF_PATH%%|/usr/local/nginx/conf/nginx.conf|" \
	-e "s|%%ERROR_LOG_PATH%%|/var/log/nginx/error.log|" \
	< man/nginx.8 > objs/nginx.8
make[1]: Leaving directory '/root/nginx-1.20.0'

objs目录以有nginx这个可执行程序
[root@localhost nginx-1.20.0]# cd objs/
[root@localhost objs]# ls
addon         Makefile  nginx.8            ngx_auto_headers.h  ngx_modules.o
autoconf.err  nginx     ngx_auto_config.h  ngx_modules.c       src

3. Back up the source program and stop, overwrite, and start the service
// First check the difference between the pre-upgrade and post-upgrade versions, mainly looking at the compilation parameters
// Before the upgrade

[root@localhost nginx-1.20.0]# objs/nginx -V
nginx version: nginx/1.20.0
built by gcc 8.5.0 20210514 (Red Hat 8.5.0-4) (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 --add-module=../echo-nginx-module-master


重新停止启动下nginx,以便程序识别
[root@localhost nginx-1.20.0]# nginx -s stop
将其原有的程序备份到/opt下
[root@localhost nginx-1.20.0]# cp /usr/local/nginx/sbin/nginx /opt/
在用新的版本覆盖掉旧的版本
[root@localhost nginx-1.20.0]# cp objs/nginx /usr/local/nginx/sbin/
cp: overwrite '/usr/local/nginx/sbin/nginx'? 
[root@localhost nginx-1.20.0]# /usr/local/nginx
nginx/        nginx-1.20.2/ 
[root@localhost nginx-1.20.0]# /usr/local/nginx/sbin/nginx 
[root@localhost nginx-1.20.0]# ss -antl
State      Recv-Q     Send-Q         Local Address:Port           Peer Address:Port     Process     
LISTEN     0          128                  0.0.0.0:22                  0.0.0.0:*                    
LISTEN     0          128                  0.0.0.0:80                  0.0.0.0:*    
[root@localhost nginx-1.20.0]# nginx -V
nginx version: nginx/1.20.0
built by gcc 8.5.0 20210514 (Red Hat 8.5.0-4) (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 --add-module=/root/echo-nginx-module-master

4. Test – reference the echo module

  #access_log  logs/host.access.log  main;

        location / {
                echo "good time";
        }

可以使用windos系统中的cmd进行
C:\Users\goodtime>curl 192.168.47.137
good time

9. Location case

The location section matches the URI requested by the client by specifying a pattern.
Function:
Allows matching of each defined location based on the URI requested by the user. When matched, the request will be processed by the configuration in the corresponding location configuration block, for example Do access control and other functions
Syntax:
location [modifier] pattern {...}
modifier
= exact match
~ Regular expression pattern matching, case-sensitive
~* Regular expression pattern matching, case-insensitive
^~ Prefix matching, similar to The behavior without modifiers also starts with the specified module. The difference is that if the pattern matches, then it stops searching for other patterns. The regular expression @ defines named location sections. These
sections cannot be accessed by the client. They can only Accessed by internally generated requests, such as try_files or error_page, etc.

1. Define a test field

[root@localhost sbin]# vim /usr/local/nginx/conf/nginx.conf
   location /hhh {
                echo "good time";
        }
[root@localhost sbin]# ./nginx -s reload

//可见不按添加的字段访问的话显示不了输出值
C:\Users\goodtime>curl 192.168.47.137
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>

C:\Users\goodtime>curl 192.168.47.137/hhh
good time

2. = Exact match
//If something else is output, an error will be reported

C:\Users\goodtime>curl 192.168.47.137 /hhh
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>

3. ~ is case-sensitive, and the search is based on the absolute path (as long as it is inside)

C:\Users\goodtime>curl 192.168.47.137/hhH
<html>
<head><title>404 Not Found</title></head>
//后面可以加任意的数值
C:\Users\goodtime>curl 192.168.47.137/hhhdadadawqeqw
good time

4. ~* is not case sensitive

C:\Users\goodtime>curl 192.168.47.137/hHh
good time

5. ^~ matches the part starting with a numerical value

C:\Users\goodtime>curl 192.168.47.137/hhh
good time

Priority order, here if everything is added to it, the rules will be matched in order of priority.

Search order and priority: from high to low
1. Exact matches with "=" are preferred
2. Regular expressions are in the order they are defined in the configuration file
3. Those with "^~" modifiers are matched at the beginning
4 , with or * modifier, if the regular expression matches the URI
5. Exact match without modifier

location = path
location ^~ path
location ~ regular (for example, you need to add $ after /hhh, ending with this)
location ~* regular
location path

1 =
2 ^~
3 ~*
4 ~
5 Countless

10. nginx access control

//Used for location segment
Allow: Set which host or hosts are allowed to access, separate multiple parameters with spaces. Deny
: Set which host or hosts are prohibited from access, separate multiple parameters with spaces
. For example:
allow 192.168 .47.137 192.168.47.136;etc.deny
all;

//View IP in local cmd system

C:\Users\goodtime>ipconfig
以太网适配器 VMware Network Adapter VMnet8:

   连接特定的 DNS 后缀 . . . . . . . :
   本地链接 IPv6 地址. . . . . . . . : fe80::70bb:164a:9969:5e53%21
   IPv4 地址 . . . . . . . . . . . . : 192.168.47.1
   子网掩码  . . . . . . . . . . . . : 255.255.255.0

模拟拒绝本机访问nginx状态页面
         location /status {
                echo "chenyu";
                deny 192.168.47.1;           //本机ip


C:\Users\goodtime>curl 192.168.47.137/status
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.20.2</center>
</body>
</html>

//Open the stub_status module

stub_status模块主要作用于查看nginx的一些状态信息
         location /status {
                stub_status on;
		}


状态
C:\Users\goodtime>curl 192.168.47.137/status
Active connections: 1
server accepts handled requests
 8 8 6
Reading: 0 Writing: 1 Waiting: 0

Analysis:
Active connections: The number of active connections currently being processed by nginx
Server accepts handled requests: nginx processed a total of 63 connections, successfully created 63 handshakes, and processed a total of 62 requests Reading
: The number of Header information nginx read from the client
Writing : The number of Header information returned by nginx to the client.
Waiting: When keep-alive is turned on, this value is equal to active- (reading+writing), which means that nginx has completed processing and is waiting for the resident connection of the next request instruction. Therefore, when the access efficiency is high and the request is processed quickly, it is normal for the waiting number to be relatively high. If the number of reading+writing is large, > indicates that the amount of concurrent access is very large and is being processed.

//When allow all exists, allow other IPs to access

   location /status {
                stub_status on;
                allow 192.168.47.1;
                allow all;
        }


测试,本机成功
C:\Users\goodtime>curl 192.168.47.137/status
Active connections: 1
server accepts handled requests
 8 8 8
Reading: 0 Writing: 1 Waiting: 0


模拟在另一台虚拟机网页中访问主机ip
[root@my ~]# ip a | grep ens32
2: ens32: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc _codel state UP group default qlen 1000
    inet 192.168.47.136/24 brd 192.168.47.255 scope global noprefixroute ens32


可以ping通nginx主机
[root@my ~]# ping 192.168.47.137
PING 192.168.47.137 (192.168.47.137) 56(84) bytes of data.
64 bytes from 192.168.47.137: icmp_seq=1 ttl=64 time=0.408 ms


[root@my ~]# curl 192.168.47.137/status
Active connections: 1 
server accepts handled requests
 13 13 13 
Reading: 0 Writing: 1 Waiting: 0 



当添加deny后
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf



location /status {
                stub_status on;
                allow 192.168.47.1;
                deny all;
        }
[root@localhost ~]# nginx -s reload


失败
[root@my ~]# curl 192.168.47.137/status
<html>
<head><title>403 Forbidden</title></head>


在测试添加136访问
allow 192.168.47.136;
[root@localhost ~]# nginx -s reload
//成功
[root@my ~]# curl 192.168.47.137/status
Active connections: 1 
server accepts handled requests
 16 16 16 
Reading: 0 Writing: 1 Waiting: 0 

1. User authentication encryption mode

Add a set of encrypted information for virtual machine users, so that when logging into the virtual machine interface, they will be asked to enter an encrypted password to ensure their security.

//授权用户
安装httpd-tools软件包
[root@localhost ~]# yum -y install httpd-tools


//创建用户密钥文件
[root@localhost ~]# cd /usr/local/nginx/conf/
//这里的密码为加密后的密码串,建议用htpasswd来创建文件,这里创建的jr用户是不存在系统中的
[root@localhost conf]# htpasswd -c -m .user_auth_file jr
New password: 
Re-type new password: 
Adding password for user jr
//密码信息
[root@localhost conf]# cat .user_auth_file 
jr:$apr1$ma8B3sAP$r24RhqreiU0O2pqBLnUNq/

//配置nginx(注意auth_basic_user_file必须用绝对路径)
[root@localhost conf]# vim nginx.conf
[root@localhost conf]# nginx -s reload
  location /status {
                stub_status on;
                auth_basic "欢迎光临";
                auth_basic_user_file "/usr/local/nginx/conf/.user_auth_file";
        }

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-d9SvLFy5-1666173270394)(./1665654224926.png)]

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-ZYogn81M-1666173270395)(./1665654235330.png)]

2. https configuration

Nginx:192.168.47.137
CA:192.168.47.136

//Generate a pair of keys in the CA server

[root@CA ~]# mkdir  -p  /etc/pki/CA/private
[root@CA ~]# cd /etc/pki/CA/
//生成私钥
[root@CA CA]# (umask 077;openssl genrsa -out private/cakey.pem 2048)
Generating RSA private key, 2048 bit long modulus (2 primes)
.....+++++
...........+++++
e is 65537 (0x010001)
//生成公钥
[root@CA CA]# openssl rsa -in private/cakey.pem -pubout
writing RSA key
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuQfU9CLxicvy7XggXSSB
KJp/6VrVd6iHqG8Rfv89kx0X/AOXPKFHrTDiDj1fxwTNDOhPNSTXXVybxgjAdfXT
03DmbgFYoXp6C+SqeetdiDD3NbIBRJjyFb5bgXXt0Se11vN0oDPzp6PowRH+VhFI
gfsvdjpMvaDmuEoYwnefA5SjP4gO4i0CNdu8PSy/JFgXz7NGinp4Eiqxt5Ljtthj
IljqH6yIbuYoao2oW0GrPfFe5hhkKu8cXredNhFD5uz9HJU/ziwPecVqo88FC2af
8GtQCfBGRTewqkoTcLLoIsPum58aVvomnF0t5IU0hcpGl7jlqndk6dnBlqGNTrOp
OwIDAQAB
-----END PUBLIC KEY-----
生成自属签名颁发证书,并导入到cacert.pem中
[root@CA CA]# openssl req -new -x509 -key private/cakey.pem -out cacert.pem -days 1024
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:HB
Locality Name (eg, city) [Default City]:WH
Organization Name (eg, company) [Default Company Ltd]:HH^H
Organizational Unit Name (eg, section) []:linux
Common Name (eg, your name or your server's hostname) []:LL
Email Address []:[email protected]

//Generate certificate signing request in nginix and send to CA

[root@localhost ~]# cd /usr/local/nginx/conf/
//生成私钥
[root@localhost conf]# (umask 077;openssl genrsa -out httpd.key 2048)
Generating RSA private key, 2048 bit long modulus (2 primes)
......+++++
...................................+++++
e is 65537 (0x010001)
//在生成一个请求,保持一个合同同步允许确认证书通过
[root@localhost conf]# openssl req -new -key httpd.key -days 1024 -out httpd.csr
Ignoring -days; not generating a certificate
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:HB
Locality Name (eg, city) [Default City]:WH
Organization Name (eg, company) [Default Company Ltd]:HH^H
Organizational Unit Name (eg, section) []:linux
Common Name (eg, your name or your server's hostname) []:LL
Email Address []:[email protected]

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
[root@localhost conf]# ls
httpd.csr        httpd.key
//发送证书             
[root@localhost conf]# scp httpd.csr [email protected]:/root/
[email protected]'s password: 
httpd.csr                                       100% 1017   723.0KB/s   00:00  

//View in CA host

[root@CA ~]# ls
anaconda-ks.cfg  httpd.csr
//CA签署证书并发送给NGINX
[root@CA ~]# mkdir /etc/pki/CA/newcerts          //将来颁发证书的存放路径
[root@CA ~]# touch /etc/pki/CA/index.txt          //网页数据显示
[root@CA ~]# echo "01" > /etc/pki/CA/serial       //设置序列号
//重新对证书进行签名,并生成httpd.crt
[root@CA ~]#  openssl ca -in httpd.csr -out httpd.crt -days 1024
Using configuration from /etc/pki/tls/openssl.cnf 
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number: 1 (0x1)
        Validity
            Not Before: Oct 13 09:50:22 2022 GMT
            Not After : Aug  2 09:50:22 2025 GMT
        Subject:
            countryName               = CN
            stateOrProvinceName       = HB
            organizationName          = HH\08
            organizationalUnitName    = linux
            commonName                = LL
            emailAddress              = [email protected]
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            Netscape Comment: 
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier: 
                B9:E3:DC:E2:75:93:5A:8C:82:FD:80:30:75:99:CC:C5:5A:95:3B:56
            X509v3 Authority Key Identifier: 
                keyid:2C:A2:DB:98:54:06:EB:2D:24:A8:84:E4:8E:71:36:D0:70:88:BC:2D

Certificate is to be certified until Aug  2 09:50:22 2025 GMT (1024 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated
[root@CA ~]# ls
anaconda-ks.cfg  httpd.crt  httpd.csr



//将CA签署的证书httpd.crt和服务器的证书cacert.pem(密钥信息)发送给nginx
[root@CA ~]# scp httpd.crt [email protected]:/usr/local/nginx/conf/ 
The authenticity of host '192.168.47.137 (192.168.47.137)' can't be established.
ECDSA key fingerprint is SHA256:cdmo9f87/nd53T0zrSlRNvEDKskgEb2tSwNZINSW84U.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '192.168.47.137' (ECDSA) to the list of known hosts.
[email protected]'s password: 
httpd.crt                                              100% 4517     2.8MB/s   00:00    
[root@CA ~]# scp /etc/pki/CA/[email protected]:/usr/local/nginx/conf/
[email protected]'s password: 
cacert.pem                                             100% 1367     1.4MB/s   00:00 

//nginx configuration https

[root@localhost conf]# vim /usr/local/nginx/conf/nginx.conf
 server {
        listen       443 ssl;                      //监听443加密
        server_name  localhost;
        ssl_certificate httpd.crt;              //证书位置
        ssl_certificate_key httpd.key;          //私钥信息
        ssl_session_cache    shared:SSL:1m;      //链接缓存
        ssl_session_timeout  5m;
        ssl_ciphers  HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers  on;

        location / {
            root   html;
            index  index.html index.htm;
        }

[root@localhost conf]# nginx -s reload
[root@localhost html]# echo "jrhh" > index.html 
[root@localhost html]# nginx -s reload

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-ZdGh5n1t-1666173270395)(./1665654999590.png)]

11. Rewrite redirection

Like apache and other web service software, the main function of rewrite is to redirect URL addresses. The rewrite function of Nginx requires the support of PCRE software, which uses perl-compatible regular expression statements for rule matching. Compiling nginx with default parameters will support the rewrite module, but it must also be supported by PCRE.

The Rewirte function is to use the global variables provided by nginx or the variables set by yourself, combined with regular expressions and tag bits to implement URL rewriting and redirection.

Rewrite can only be placed in server{}, location{}, if{}, and by default it can only work on the string after the domain name excluding the passed parameters. For example, http://www.cy.com/abc/aa/index.php?a=1&b=2 only rewrites /abc/aa/index.php

URL: It is a specific path/location.
URI: refers to a collection of objects with the same type/characteristics.
URL address, commonly known as web page address, or URL for short, is a string used to completely describe the address of web pages and other resources on the Internet
[External link picture The transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-0uDhliX2-1666173614317)(./1665804328382.png)] Nginx: supports URL rewriting
through the ngx_http_rewrite_module module and supports if condition judgment, but else is not supported.
Jump: Jump from one location to another. The loop can be executed up to 10 times. After that, nginx will return a 500 error.
PCRE support: perl-compatible regular expression syntax rule matching
Rewrite module set directive: create new variables and set their values

//Grammar format:
rewrite [flag];
regex: indicates the regular matching rule
replacement: indicates the content after the jump
flag: indicates the flag mark supported by rewrite

//flag mark description:
last: After the matching of this rule is completed, continue to match the new location URL rule downwards, generally used in server and if.
break: This rule is terminated when the matching is completed. It does not match any rules after it. It is generally used in location.
redirect: Returning 302 temporary redirect represents a temporary jump. When the user accesses a page, the server will return a 302 status code to tell the browser that the page has been redirected. You must manually redirect the browser to the new URL. The browser address will display the URL address after the jump.
permanent: Return 301 permanent redirect, and the browser address bar will display the URL address after the jump.

Matching regular identifiers and meanings
^ must start with the entity after ^ and
must end with the entity before $
. Match any single character
[] Match any character in the specified character set
[^] Match any character not included in the specified character set Any string
| matches the entity () grouping before or after
| to form a group of entities for matching, usually with | to assist
\ escaping

  • *** matches the previous character appearing zero or more times. For example, "ab*" can match a, ab, abb
  • +\ matches the previous character appearing one or more times. For example, "ab+" can match ab, abb, but not a.
  • ? Match the previous character appearing zero or once, such as "ab(cd)?" can match ab, abcd

(pattern) matches the pattern in the brackets and can obtain the corresponding match later. The $0-9 attribute is commonly used to obtain the matching content in the parentheses. For example, the (hello ∣ chenyu) 9 attribute obtains the matching content in parentheses. For example, the ^(hello | chenyu)9 attribute obtains the matching content in parentheses. Such as ( h e ll**oc h e n y**u ) //The string is "hello chenyu", and the captured results are:
$1=hello$2=chenyu These captured data can be used later Used as a variable

The rewrite function of nginx is widely used in enterprises.
1. It can adjust the URL that users browse to make it look more standardized and meet the needs of developers and product personnel.
2. In order to allow search engines to search website content and provide a better user experience, enterprises will The dynamic URL address is disguised as a static address to provide services
3. After the domain name is updated, old visits will jump to the new domain name. For example, access to JD.com's 360buy.com will jump to jd.com
4. According to special variables and directories , client information for URL adjustment, etc.

1. rewrite configuration

//nginx accesses Xiaolizi’s custom web page

[root@localhost ~]# cd /usr/local/nginx/html/
[root@localhost html]# ls
50x.html  index.html
[root@localhost html]# mkdir imgs
[root@localhost html]# cd imgs/
[root@localhost images]# ls
xlz.jpg
[root@localhost imgs]# vim /usr/local/nginx/conf/nginx.conf
location = /imgs {
        }
[root@localhost imgs]# nginx -s reload

Really handsome!
[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-6vnYmRkc-1666173614318)(./1665755821173.png)]

2. flag mark –break

break: This rule is terminated when the matching is completed. It does not match any rules after it. It is generally used in location.
//Need to write rewrite
//The absolute path of the web page is /images/, but making it a variable is different.

[root@localhost html]# vim /usr/local/nginx/conf/nginx.conf
  location = /imgs {
                rewrite ^/imgs/(.*\.jpg)$ /images/$1 break;       //$定义正则表达式访问网页
        }

[root@localhost images]# nginx -s reload

The access is still imgs
[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-76R9cQi1-1666173614318)(./1665757889785.png)]

//We can also use break to jump to Baidu's homepage
location /imgs { rewrite ^/imgs/(.*.jpg)$ http://www.baidu.com break; }

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-BHEbskjA-1666173614319)(./1665758229034.png)]

3. flag mark-last

last: After the matching of this rule is completed, continue to match the new location URL rule downwards, generally used in server and if.
//Match multiple values ​​and jump to the free music listening website (share)

[root@localhost html]# vim /usr/local/nginx/conf/nginx.conf
   location /imgs {
                rewrite ^/imgs/(.*\.jpg)$ /images/$1 last;
        }
        location /images {
                rewrite ^/images/(.*\.jpg)$ https://music.y444.cn/#/ last;
        }

[root@localhost html]# nginx -s reload

//Can be used to listen to Jay's songs while studying
[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-6G2xvbLN-1666173614319)(./1665758631629.png)]

4. flag mark –redirect

redirect: Returning 302 temporary redirect represents a temporary jump. When the user accesses a page, the server will return a 302 status code to tell the browser that the page has been redirected. You must manually redirect the browser to the new URL, and the browser address will display the URL address after the jump.

   location /imgs {
                rewrite ^/imgs/(.*\.jpg)$ /images/$1 redirect;
        }

//Press F12 for status monitoring
and F5 to refresh the web page.
[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-x4xiivh4-1666173614320)(./1665759378483.png)]

5. flag mark – permanent

Return to 301 permanent redirection, and the browser address bar will display the URL address after the jump.

[root@localhost html]# vim /usr/local/nginx/conf/nginx.conf

       location /imgs {
                rewrite ^/imgs/(.*\.jpg)$ /images/$1 permanent;
        }
[root@localhost html]# nginx -s reload

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-U7rcwXuZ-1666173614320)(./1665759612819.png)]

6. if judgment

Can be used in the server segment and location segment.
Syntax:
if (condition) {...}
Common conditions:
(1) variable name
(2) comparison expression composed of variable name and operand (you can use =, != similar comparisons Characters are tested)
(3) Pattern matching operation of regular expressions

  • ~ Case-sensitive pattern matching checks
  • ~* Case-insensitive pattern check
    (4) Test the possibility that the specified path is a file (-f !-f)
    (5) Test the possibility that the specified path is a directory (-d !-d)
    (6) Test file The existence of (-e !-e)
    (7) Check whether the file has execution permission (-x !-x)

6.1. Configure domain name-based redirection

If the company's old domain name www.lty.com now has business needs, it needs to be replaced by the new domain name www.liutianyang.com. However, the old domain name cannot be abolished and needs to jump to the new domain name, and the following parameters remain unchanged
/ /Modify the nginx server host name www.lty.com

[root@localhost html]# hostnamectl set-hostname www.lty.com
[root@localhost html]# bash
[root@www html]# 

//将本机两个域名映射关系写入到/etc/hosts中,并传给客户端
[root@localhost html]# vim /etc/hosts 
192.168.47.137 www.lty.com
192.168.47.137 www.liutianyang.comm
[root@localhost html]# scp /etc/hosts [email protected]:/etc/hosts
[email protected]'s password: 
hosts                                     100%  220    42.1KB/s   00:00 
//修改配置文件,写入rewrite和if结合使用
[root@www html]# vim /usr/local/nginx/conf/nginx.conf
  server {
        listen       80;
        server_name  www.lty.com;
        
       location / {
                if ($host = 'www.lty.com') {
                        rewrite ^/(.*)$ http://www.liutianuang.com/$1 permanent;
                }
                root html;
                index index.html index.htm;
      
[root@www html]# echo "This is a test" > /usr/local/nginx/html/index.html
[root@www html]# nginx -s reload

//The client uses a browser to access – http://www.lty.com – we will find that it automatically jumps to the new domain name www.liutianuang.com
[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-3FwBIWPO-1666173614321)(./1665798296829.png)]

6.2. Access jump based on client IP

If a new version of the company's business is launched today, it requires all IPs to access any content to display a fixed maintenance page. Only the company IP: 192.168.47.50 can access normally.

[root@www html]# vim /usr/local/nginx/conf/nginx.conf
  server {
        listen       80;
        server_name  www.lty.com;
        set $rewrite true;                         //开启重写规则
        if ($remote_addr = "192.168.47.50") {          //如果判断等于对应的ip则成立
                set $rewrite false;                                   //关闭重写
        }

        if ($rewrite = true) {    //当变量判断是其他ip成立时
                rewrite (.+) /weihu.html;   //.+代表配合任何ip并以/网页状态显示
        }
[root@www html]# nginx -s reload
//新建/var/www/html目录,并往该目录下写入文件weihu.html,内容为weihu
[root@www html]# mkdir /var/www/html -p
[root@www html]# echo "in  weihuing" >  /var/www/html/weihu.html

Verification:
50 client visits
[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-XW38lcHj-1666173614322)(./1665799618879.png)]

137 terminal access
[root@www html]# curl http://www.lty.com
in weihuing

7. Browser-based separation

//Create the following directories and files in the /usr/local/nginx/html directory

[root@www html]# mkdir firefox chrome
[root@www html]# echo "firefox test" > firefox/index.html
[root@www html]# echo "chrome test" > chrome/index.html

//修改配置文件
[root@www html]# vim /usr/local/nginx/conf/nginx.conf
server {
        listen       80;
        server_name  localhost;


        location / {
                if ($http_user_agent ~ Firefox) {
                        rewrite ^(.*)$ /firefox/$1 break;
                }

                if ($http_user_agent ~ Chrome) {
                        rewrite ^(.*)$ /chrome/$1 break;
                }
                root html;
                index index.html index.htm;
        }

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location /firefox {
                root html;
                index index.html;
        }
        location /chrome {
                root html;
                index index.html;
        }
[root@www html]# 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
[root@www html]# nginx -s reload

Verification
1. Chrome Google browser access
[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-TAbbCnTo-1666173614322)(./1665801439953.png)]

2. Firefox browser access
[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-4YElJ7Qq-1666173614323)(./1665801467016.png)]

12. Anti-hotlink cases

Before understanding the principle of anti-leeching, we must first learn the Referer header information of HTTP. When the browser sends a request to the web server, it usually brings the Referer to tell the browser which page the web page is linked from.

The backend server can determine whether it is a website address it trusts based on the obtained Referer information. If so, it will allow continued access. If not, it can return a 403 (server denied access) status information.
[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-vHETmPaF-1666173614324)(./1665801507579.png)]

语法:
valid_referers none blocked server_names string

  • none: If the Referer in the Header is empty, access is allowed
  • blocked: The Referer in the Header is not empty, but the value is disguised by the firewall or proxy. For example, resources without "http://", "https://" and other protocol headers are allowed to access.
  • server_names: Specify a specific domain name or IP
  • string: Can support regular expressions and * strings. If it is a regular expression, it needs to start with ~. Case
    :
    //Create the abc directory in the /usr/local/nginx/html directory and put a picture into this directory.
[root@www html]# mkdir abc
[root@www html]# cd abc/
[root@www abc]# ls
悟蓝.png

[root@www abc]# vim /usr/local/nginx/conf/nginx.conf
  location ~* \.(jpg|png) {
                root html/abc;
        }
[root@www abc]# nginx -s reload

Insert image description here

//Use the command to view the referer information. Anti-hotlink protection has not been configured yet](https://img-blog.csdnimg.cn/a37ddec96be740919d774758e2c9ebaf.png)

[root@www abc]# curl --referer http://baidu.com -I http://192.168.47.137/悟 蓝.png
HTTP/1.1 200 OK
Server: nginx/1.20.2
Date: Sat, 15 Oct 2022 02:57:12 GMT
Content-Type: image/png
Content-Length: 540902
Last-Modified: Sat, 15 Oct 2022 02:50:36 GMT
Connection: keep-alive
ETag: "634a1ffc-840e6"
Accept-Ranges: bytes

The status here also has no header
! [(img-qMmq8inY-1666173614326)(./1665802902479.png)]](https://img-blog.csdnimg.cn/37419da8250649189bf993c83695dd1c.png)

1. Start configuring anti-hotlinking

[root@www html]# vim /usr/local/nginx/conf/nginx.conf
   location ~* \.(jpg|png) {                 //以~开始正则匹配(jpg|png)为结尾的后缀
                root html/abc;
                valid_referers  blocked www.cy.com;        //如果返回的头部referer为www.lty.com那么就不会执行valid_referer下面内容   
                if ($invalid_referer) {        //反之则会生成防盗链
                        return 403;
                        break;
                }
        }
[root@www html]# nginx -s reload

There is no need to add the none parameter here. This form of access is to directly request the 1.jpg file in the default html in the server. There is no header (only two or more requests will have the referer header), and we have it in the configuration file. The [none] parameter has been added, which means that we can still access the file when there is no header referer, so the anti-hotlink protection we configured does not work at this time.

verify:
[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-p5p7e28C-1666173614327)(./1665804020215.png)]

[root@www html]# curl --referer http://baidu.com -I http://192.168.47.137/悟蓝.png
HTTP/1.1 403 Forbidden
Server: nginx/1.20.2
Date: Sat, 15 Oct 2022 03:19:57 GMT
Content-Type: text/html
Content-Length: 153
Connection: keep-alive

13. Reverse proxy and load balancing

  1. nginx is usually used as a reverse proxy for back-end servers, so that dynamic and static separation and load balancing can be easily achieved, thereby greatly improving the server's processing capabilities.
  2. nginx realizes dynamic and static separation. In fact, during reverse proxy, if it is a static resource, it can be read directly from the path published by nginx, without the need to obtain it from the backend server.
  3. However, it should be noted that in this case, it is necessary to ensure that the back-end and front-end programs are consistent. You can use Rsync for automatic server-side synchronization or use NFS or MFS distributed shared storage.
    • The Http Proxy module has many functions. The most commonly used ones are proxy_pass and proxy_cache.
      If you want to use proxy_cache, you need to integrate the third-party ngx_cache_purge module to clear the specified URL cache. This integration needs to be done when installing nginx, such as:
      ./configure --add-module=…/ngx_cache_purge-1.0…

1. What is an agent?

Speaking of agents, first we have to clarify a concept. The so-called agent is a representative and a channel.
At this time, we design two roles, one is the agent role, and the other is the target role. The agent role accesses the target role through this agent. The process of some tasks is called the agent operation process; just like a specialty store in life ~ a customer goes to a certain Das specialty store and buys a pair of shoes. This specialty store is the agent, the agent role is a certain Das manufacturer, and the target role is the user

2. Forward proxy

Such a proxy mode is called a forward proxy. The biggest feature of a forward proxy is that the client is very clear about the server address it wants to access; the server only knows which proxy server the request comes from, but not which specific client it comes from; forward proxy mode Real client information is blocked or hidden.
blob:https://maxiang.io/34804c1c-8b3d-406f-9658-8923f38d07b0

3. Reverse proxy

After receiving the requests sent by multiple clients to the server, the nginx server distributes them to the back-end business processing server for processing according to certain rules. At this time, the source of the request is clear, that is, the client, but it is not clear which server handles the request. nginx plays the role of a reverse proxy.

Reverse proxy is mainly used in distributed deployment of server clusters. Reverse proxy hides server information!
[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-uj7OjlcK-1666168246998)(./1666151082692.png)]

//In actual production projects, most of them use a combination of forward proxy and reverse proxy.

When we operate the actual project, forward proxy and reverse proxy are likely to exist in an application scenario. The forward proxy proxy client's request to access the target server, the target server is a reverse proxy server, and the reverse proxy is Multiple real business processing servers

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-OUksK3Mh-1666168247000)(./1666151102613.png)]

4. Load balancing

  • nginx implements simple load balancing through the upstream module. Upstream needs to be defined in the http segment.
  • Weight polling (default): The received requests are assigned to different back-end servers one by one in order. Even if a back-end server goes down during use, nginx will automatically remove the server from the queue and request acceptance status will not be affected in any way.
  • In this way, a weight value (weight) can be set for different back-end servers to adjust the allocation rate of requests on different servers; the larger the weight data, the greater the probability of being allocated to the request; the weight value, It is mainly adjusted for different back-end server hardware configurations in actual working environments.
  • ip_hash: Each request is matched according to the hash result of the initiating client's IP. Under this algorithm, a client with a fixed IP address will always access the same back-end server. This also solves the problem of session in a cluster deployment environment to a certain extent. Shared issues.

5. Nginx load balancing case

Host Ip Install system
Nginx 192.168.47.137 Nginx RHEL8
Rs1 192.168.47.136 Httpd RHEL8
Rs2 192.168.47.50 Httpd RHEL8

//Turn off the firewall and selinux on all three hosts, and configure the yum warehouse
//The nginx host deploys the nginx service. It has been deployed before, so I will not demonstrate it here.
//On the rs1 host, install httpd, and then add a test Web page

[root@rs1 ~]# yum -y install httpd
[root@rs1 ~]# systemctl restart httpd
[root@rs1 ~]# systemctl enable --now httpd
[root@rs1 ~]# echo "This is a server1" > /var/www/html/index.html
[root@rs1 ~]# cat /var/www/html/index.html 
This is a server1
[root@rs1 ~]# systemctl restart httpd

//On the rs2 host, install httpd, and then add a test web page

[root@rs2 ~]# yum -y install httpd
[root@rs2 ~]# systemctl restart httpd.service 
[root@rs2 ~]# systemctl enable --now httpd.service 
[root@rs2 ~]# echo "This is a server2" > /var/www/html/index.html
[root@rs2 ~]# systemctl restart httpd.service 

//On the nginx host, modify the configuration file and set load balancing

[root@www ~]# vim /usr/local/nginx/conf/nginx.conf
http {
        upstream webserver {                    //定义负载模块为webserver
        server 192.168.47.136;
        server 192.168.47.50;
}

  server {
        listen       80;
        server_name  localhost;
        
  location / {
                proxy_pass http://webserver;
        }
[root@www ~]# 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
[root@www ~]# nginx -s reload

//Use nginx ip to access
[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-Ha9eQIps-1666168247001)(./1666151821145.png)]
server2
[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-pX3pwq19-1666168247002)(./1666151837666.png)]
load balancing setting successfully

6. Set load balancing weights

If you want one of the back-end real servers to have enough data and bear more visits, you can use weight to set the weight of the requested access.

[root@www ~]# vim /usr/local/nginx/conf/nginx.conf
http {
        upstream webserver {
        server 192.168.47.136 weight=2;     ///添加此行
        server 192.168.47.50;
}
[root@www ~]# nginx -s reload

Reload nginx and test access. At this time, you will find that 47.136 is accessed 2 times by the host (rs1) before being polled to rs2.

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-tPjEKxYz-1666168247002)(./1666152292189.png)]

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-6IERC8z8-1666168247003)(./1666152293881.png)]

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-bNUwoqxY-1666168247003)(./1666152307993.png)]

7. Test access to different ports

//At this time, we found that the three hosts all use port 80, so the upstream used in the nginx configuration file corresponds to the real backend server. If we do not set the port, what if one of the backend servers uses port 8080? How do we set up, rs1 is port 8080, rs2 is port 80
//First modify the httpd service of rs1, listen to port 8080, and restart the httpd service

[root@www ~]# vim /usr/local/nginx/conf/nginx.conf

http {
        upstream webserver {
        server 192.168.47.136:8080 weight=2;
        server 192.168.47.50:80;
}
[root@www ~]# nginx -s reload

//第一台服务端修改端口
[root@rs1 ~]# vim /etc/httpd/conf/httpd.conf 
Listen 8080
[root@rs1 ~]# systemctl restart httpd
[root@rs1 ~]# ss -antl | grep 8080
LISTEN 0      128                *:8080            *:*    

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-3leMTIWR-1666168247005)(./1666152657490.png)]

8. ip_hash configuration

[root@www ~]# vim /usr/local/nginx/conf/nginx.conf
http {
        upstream webserver {
        ip_hash
        server 192.168.47.136:8080 weight=2;
        server 192.168.47.50:80;
}
[root@www ~]# nginx -s reload

According to my personal understanding, the load balancing mode of ip_hash is: for example, multiple users access the back-end httpd cluster through nginx. At this time, because there are different users, the IPs are also different, and the hash values ​​calculated by the ip+hash algorithm are transmitted to httpd. nginx records the IP and hash value, so the next time the same IP comes over, it will still be assigned to the httpd.

  • If a server in the cluster fails and we want to remove it from the nginx cluster configuration, we cannot directly delete that line, such as server 192.168.100.10:8080 weight=2
    ; delete, if Direct deletion will cause nginx's hash algorithm to be recalculated, and the user's session or cache will be invalidated. Therefore, if this server is not used here, just compare it directly to down, that is, server 192.168.100.10:8080 down. This
    is That's it.

9. Separation of dynamic and static nginx+tomcat

Or add an additional tomcat based on the above environment
Tomcat: 192.168.47.50

//If you want to deploy tomcat, you can look at the tomcat in my previous jenkins service deployment. I will omit it at this time. After deployment, let's test access the following dynamic test webpage based on tomcat.

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-9A9Vw5WC-1666168247006)(./1666155354420.png)]
nginx side deployment

[root@www ~]# vim /usr/local/nginx/conf/nginx.conf
http {
        upstream static {
        server 192.168.47.136;
        server 192.168.47.148 weight=2;   
}
        upstream tomcat {                           //动态测试
                server 192.168.47.50:8080;
        }


 server {
        listen       80;
        server_name  localhost;


        location / {
                proxy_pass http://static;
        }

        location /jenkins {
                proxy_pass http://tomcat;
        }
        
[root@www ~]# nginx -s reload

Static page access successful
[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-g3c2UkU2-1666168247007)(./1666157238625.png)]

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-8DSfDCmc-1666168247008)(./1666157245983.png)]

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-yAjV9GWu-1666168247008)(./1666157253986.png)]
dynamic access
[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-ng9d4gqW-1666168247009)(./1666157287451.png)]

Guess you like

Origin blog.csdn.net/qq_36306519/article/details/131097273