Nginx website service (installation of nginx, smooth upgrade of nginx, various access configurations of nginx)

1. Overview of Nginx

1. What is nginx?

  • High stability, low system resource consumption,
  • High processing capacity for concurrent HTTP connections (a single physical machine can support 30,000-50,000 concurrent requests)
NG并发连接能力有2个因素的影响
①CPU的个数
②本地吴立琪系统的最大文件打开数

2. Nginx application scenarios

Static server (picture, video service)

dynamic service

reverse proxy, load balancing

cache service

Reverse proxy explanation: It means that users do not need to know the address of the target server, and do not need to make any settings on the client side. They can directly access the reverse proxy server to obtain the resources of the target server. Secure, accelerated access to internal servers.

Advantages of reverse proxy:

①Improved the security of the internal server

②Speed ​​up the access speed of reading i internal server

③ Save limited IP resources

3. Nginx application enterprise

Because the specificity of nginx is that it has less internal memory and strong concurrency.

Domestic users using nginx websites include:  Baidu, BWS, Sina, Netease, Tencent, etc.

However,  Taobao  carried out secondary development on the principle of GPL, and the current  Tengine website appeared.

4. HTTPD seven-layer proxy and four-layer proxy of nginx

Nginx's http seven-layer proxy, nginx works in the application of the OSI seven-layer model, because it can analyze the http protocol, we can distribute requests according to the URL, which has great flexibility, but there is performance consumption in the analysis of the protocol, In order to obtain higher proxy performance,

nginx supports four layers of proxy, that is, the transport layer, which is the TCO/UDP layer. There is no protocol analysis, it is simple TCP/UDP forwarding, and the proxy performance is improved by leaps and bounds (  supported only after version 1.18)

Two, the difference between Nginx and Apache

Nginx is an event-based web server and Apache is a process-based server.

All Nginx requests are processed by one thread, and Apache single thread handles a single request.

Nginx is better in memory consumption and connection, Apache is average in memory consumption and connection convenience.

The performance and scalability of Nginx do not depend on hardware, while Apache depends on hardware such as CPU and memory.

Nginx supports hot deployment, Apache does not support hot deployment.

Nginx has high efficiency for static file processing, and Apache is relatively general.

Nginx has obvious advantages in reverse proxy scenarios, while Apache is relatively general.
 

3. Compile and install Nginx service

1. Turn off the firewall and transfer the software package to the /opt directory

systemctl stop firewalld
systemctl disable firewalld
setenforce 0

 

2. Install dependent packages 

nginx的配置及运行需要pcre、zlib等软件包的支持,因此需要安装这些软件的开发包,以便提供相应的库和头文件。
yum -y install pcre-devel zlib-devel gcc gcc-c++ make

4. Check whether there is a dependent environment and generate a makefile

注意:configure是一个脚本,一般由Autoconf工具生成,它会检验当前的系统环境,看是否满足安装软件所必需的条件:比如当前系统是否支持待安装软件,是否已经安装软件依赖等。configure脚本最后会生成一个Makefile文件。生成这个文件之后,才可以进行make编译。

cd /opt
tar zxvf nginx-1.12.0.tar.gz

cd nginx-1.12.0/
./configure \
--prefix=/usr/local/nginx \							#指定nginx的安装路径
--user=nginx \										#指定用户名
--group=nginx \										#指定组名
--with-http_stub_status_module						#启用 http_stub_status_module 模块以支持状态统计

 

 

 

5. Compile and install 

使用./configure进行检查之后,生成这个makefile文件,才可以进行make编译,不然会报错
make  && make install

6. Add the nginx command to the environment variable

让系统识别nginx的操作命令
ln -s /usr/local/nginx/sbin/nginx /usr/local/sbin/

 

 

7. Check, start, restart, stop nginx service

Understand the command options of kill

letter number Signal name meaning
0 EXIT Received when the program exits
1 HUP A hangup signal that hangs up a phone line or terminal connection, this signal can also cause some processes to reinitialize without terminating
2 INT Indicates the end of the process, but it is not mandatory. The commonly used "ctrl + c" key combination is this signal
3 QUIT quit
9 KILL kill process, force end process
11 SAY segment fault
15 TERM End the process normally, which is the default signal of the kill command
查看配置文件是否配置正确
nginx  -t

#启动nginx服务
nginx

#停止nginx服务
cat /usr/local/nginx/logs/nginx.pid   #先查看nginx的pid号
kill -3 【pid号】

 

8. Add Nginx system service

8.1 Method 1: Use scripts

vim /etc/init.d/nginx

#!/bin/bash
#chkconfig: 35 99 20    // 这是固定格式,2345表示运行级别,之后为开机执行顺序和关机执行顺序
#description:Nginx Service Control Script    //这也是必须的 
COM="/usr/local/nginx/sbin/nginx" 
PID="/usr/local/nginx/logs/nginx.pid"
case "$1" in
start)
  $COM
;;

stop)
  kill -s QUIT $(cat $PID)
;;

restart)
  $0 stop
  $0 start
;;

reload)
  kill -s HUP $(cat $PID)
;;

*)
echo "Usage: $0 {start|stop|restart|reload}"
exit 1
esac
exit 0

 

 

8.2 Method 2: Use the configuration file to perform 

vim /lib/systemd/system/nginx.service

[Unit]
Description=nginx
After=network.target
[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target

[Unit]:服务的说明
Description:描述服务
After:依赖,当依赖的服务启动之后再启动自定义的服务

[Service]服务运行参数的设置
Type=forking是后台运行的形式,使用此启动类型应同时指定
PIDFile以便systemd能够跟踪服务的主进程。
ExecStart为服务的具体运行命令
ExecReload为重启命令
ExecStop为停止命令
PrivateTmp=True表示给服务分配独立的临时空间
注意:启动、重启、停止命令全部要求使用绝对路径

[Install]服务安装的相关设置,可设置为多用户

编辑好脚本后,然后设置权限为754
chmod 754 /lib/systemd/system/nginx.service

 

 

 

 8. View the ip address of web page access

4. Upgrade nginx service (1.12.2 —> 1.22.0)

1. Search and download the latest version of the stable version on the official website

网址:[nginx: download](https://nginx.org/en/download.html)

 

 2. Copy the new version to the /opt directory, and then decompress it

rz 选中桌面文件进行上传,或直接拉到shell中即可
tar -zxf nginx-1.22.0.tar.gz   #解压
cd nginx-1.22.0   #进入解压后的目录
nginx -v   #查看当前版本

 

 3. Close the nginx service (you can leave it open)

cat /usr/local/nginx/logs/nginx.pid  #查看进程号
kill -3  【pid】   #退出进程

 

  4. Install dependent packages

依赖包必须要安装,不然使用./configure 进行检查时,发现没有依赖包,导致make编译不成功
yum -y install gcc openssl openssl-devel pcre-devel zlib zlib-devel

 5. Check the target characteristics of the installation platform

cd /nginx-1.22.0/
./configure \
--prefix=/usr/local/nginx \		
--user=nginx \					
--group=nginx \					
--with-http_stub_status_module \
--with-http_ssl_module

6. Compile 

make    #只需要进行编译,不能安装,不然覆盖了之前的版本

7. Back up the old version of nginx 

将可执行命令程序进行修改名称
mv /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx_old  

复制新版本的命令程序到安装的目录
cp objs/nginx /usr/local/nginx/sbin/nginx

 8. Restart the service and check the version

 

nginx   #启动服务
nginx -v  #查看版本

 9. Verification

 

Five, understand the main configuration file of Nginx service 

配置文件路径:/uar/local/nginx/conf/nginx.conf

1. Global configuration

#user nobody; 					#运行用户,若编译时未指定则默认为 nobody
worker_processes 4; 			#工作进程数量,可配置成服务器内核数 * 2,如果网站访问量不大,一般设为1就够用了
#error_log logs/error.log; 		#错误日志文件的位置
#pid logs/nginx.pid; 			#PID 文件的位置

 2. I/O event configuration

events {
    use epoll; 					#使用 epoll 模型,2.6及以上版本的系统内核,建议使用epoll模型以提高性能
    worker_connections 4096; 	#每个进程处理 4096 个连接
}

#如提高每个进程的连接数还需执行“ulimit -n 65535”命令临时修改本地每个进程可以同时打开的最大文件数。
#在Linux平台上,在进行高并发TCP连接处理时,最高的并发数量都要受到系统对用户单一进程同时可打开文件数量的限制(这是因为系统为每个TCP连接都要创建一个socket句柄,每个socket句柄同时也是一个文件句柄)。

 3. HTTP configuration

When httpd is requested, it will be triggered to execute the configuration inside.

Use "http { }" to define tags, including access logs, HTTP ports, web directories, default character sets, connection
maintenance and a series of settings such as virtual web hosts and PHP parsing to be mentioned later, most of which are configured in Enclosed
within the sub-delimited tag "server { }"

 

http {
	##文件扩展名与文件类型映射表
    include       mime.types;
	##默认文件类型
    default_type  application/octet-stream;
	##日志格式设定
    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';
	##访问日志位置
    #access_log  logs/access.log  main;
	##支持文件发送(下载)
    sendfile        on;
	##此选项允许或禁止使用socket的TCP_CORK的选项(发送数据包前先缓存数据),此选项仅在使用sendfile的时候使用
    #tcp_nopush     on;
	##连接保持超时时间,单位是秒
    #keepalive_timeout  0;
    keepalive_timeout  65;
	##gzip模块设置,设置是否开启gzip压缩输出
    #gzip  on;
	
	##Web 服务的监听配置
	server {
		##监听地址及端口
		listen 80; 
		##站点域名,可以有多个,用空格隔开
		server_name www.kgc.com;
		##网页的默认字符集
		charset utf-8;
		##根目录配置
		location / {
			##网站根目录的位置/usr/local/nginx/html
			root html;
			##默认首页文件名
			index index.html index.php;
		}
		##内部错误的反馈页面
		error_page 500 502 503 504 /50x.html;
		##错误页面配置
		location = /50x.html {
			root html;
		}
	}
}

3.1 Monitoring Configuration of Web Service 

 3.2 Log format settings

$remote_addr与$http_x_forwarded_for用以记录客户端的ip地址;
$remote_user:用来记录客户端用户名称;
$time_local: 用来记录访问时间与时区;
$request: 用来记录请求的url与http协议;
$status: 用来记录请求状态;成功是200,
$body_bytes_sent :记录发送给客户端文件主体内容大小;
$http_referer:用来记录从哪个页面链接访问过来的;
$http_user_agent:记录客户浏览器的相关信息;
通常web服务器放在反向代理的后面,这样就不能获取到客户的IP地址了,通过$remote_add拿到的IP地址是反向代理服务器的iP地址。反向代理服务器在转发请求的http头信息中,可以增加x_forwarded_for信息,用以记录原有客户端的IP地址和原来客户端的请求的服务器地址。

location常见配置指令,root、alias、proxy_pass
root(根路径配置):root /var/www/html
请求www.kgc.com/test/1.html,会返回文件/var/www/html/test/1.html

alias(别名配置):alias /var/www/html
请求www.kgc.com/test/1.html,会返回文件/var/www/html/1.html

proxy_pass(反向代理配置)

Nginx website service
A high-performance, lightweight web service software,
high stability
, low system resource consumption,
high processing capacity for HTTP concurrent connections, a single physical server can support 30,000~50,000 concurrent requests.
(In actual operation, many companies will set it at about 20,000 for the stability of the server)

Nginx function introduction
Nginx is a high-performance open source web server and reverse proxy server, which has the following main functions:

Static file service: Nginx can directly serve static files, such as HTML, CSS, JavaScript, images, etc.
It efficiently handles and responds to requests for static files.

Reverse proxy: Nginx can act as a reverse proxy server, forwarding client requests to multiple backend servers.
It enables load balancing, high availability and failover, providing better performance and reliability.

Dynamic content processing: Nginx can be used in conjunction with back-end application servers (such as PHP-FPM, Node.js, Java application servers, etc.)
to process and execute dynamic content. It can proxy dynamic requests and return the results of the requests to the client.

SSL/TLS encryption support: Nginx supports encrypting communication between client and server via SSL/TLS,
providing a secure HTTPS connection.

Virtual host support: Nginx supports configuring multiple virtual hosts, so that multiple domain names or sites can be hosted on the same server.
Each virtual host can have independent configuration and resources.

URL rewriting and redirection: Nginx supports flexible URL rewriting and redirection rules, which can modify and redirect requested URLs to
implement URL beautification and redirection strategies.

Caching mechanism: Nginx provides a powerful caching function that can cache static files and dynamic content
to reduce the load on the back-end server and provide faster response speed.

Logging: Nginx can record access logs and error logs, and can record detailed information of requests, including access time, request path,
IP, response status, etc., to help with troubleshooting and performance analysis.

Scalability and flexibility: Nginx's modular architecture and powerful configuration options make it highly scalable and flexible.
You can meet specific needs by loading different modules and custom configurations.


Tengine:
Tengine is a web server project initiated by Taobao.com. On the basis of Nginx, it adds
many advanced functions and features to meet the needs of websites with a large number of visits. The performance and stability of Tengine have been well tested on large websites such as Taobao and Tmall
. (It can be understood in this way: after Taobao got the Nginx source code, it filled in functions, optimized it, etc., and then submitted it to the official
Nginx, but because the official Nginx response was slow or even unresponsive, and the language communication was not smooth, Taobao The company packs it by itself
, and the current version of Tengine is released)


Basic features
Modular design, better scalability
High reliability
Support hot deployment: update configuration files without stopping, upgrade version, replace log files
Low memory consumption: 10000 inactive connections in keep-alive connection mode, only 2.5 M memory


Web service-related functions
Virtual host (server)
supports keep-alive and pipeline connections (using one connection to make multiple requests)
access log (supports log buffering to improve its performance)
url rewirte
path alias
IP-based and user-based access control
support rate Restriction and concurrency limit
Reconfiguration and online upgrade without interrupting the customer's work process 

nginx application scenarios
static server (picture, video service, text)
dynamic service
reverse proxy, load balancing
cache service

The difference between Apache and Nginx
Nginx Apache
nginx is an event-based web server apache is a process-based server
All requests are processed by one thread A single thread handles a single request
nginx avoids the concept of sub-processes apache is sub-process based
nginx is similar to speed apache is similar to power
nginx is better in memory consumption and connections apache is not improved in memory consumption and connections
nginx is better in load balancing apache will reject new connections when the traffic reaches the process limit.
nginx does not support the same os as IBMI and openvms apache supports more os
nginx only has core functions apache provides more functions than nginx
performance and scalability of nginx does not depend on hardware apache depends on hardware components such as cpu and memory
nginx Support hot deployment Apache does not support hot deployment
Hot deployment is to upgrade the software while the application is running without restarting the application

Advantages of Nginx over Apache:
lightweight, nginx takes up less memory and resources than apache;
static processing, Nginx static processing performance is higher than Apache;
Nginx can achieve reverse proxy acceleration without caching and improve website speed;
Nginx's Performance and scalability do not depend on hardware, while Apache depends on hardware;
Nginx supports hot deployment, starts quickly, and can upgrade software version or configuration without interrupting service;
nginx is an asynchronous process, and multiple connections can Corresponds to one process; apache is a synchronous multi-process, one connection corresponds to one process;
Nginx is highly modular, writing modules is relatively simple, and has fewer components than Apache. High
concurrency nginx can maintain low resource consumption and high performance;
Nginx configuration is simple, Apache configuration complex;

Advantages of apache over nginx:

Rewrite is more powerful than nginx's rewrite (the main function of rewrite is to realize the URL jump of the uniform resource locator). There are
many modules, and you can find almost everything you can think of.
Few bugs, and nginx has relatively many bugs.
Ultra-stable
Nginx is weak in handling dynamic requests. Request to Apache to do it.

Classic question 1: How does Nginx achieve high concurrency? 
Asynchronous, non-blocking, using epoll and a lot of underlying code optimization.
If a server adopts the method that one process is responsible for one request, then the number of processes is the number of concurrency.
Under normal circumstances, there will be many processes waiting all the time.
And nginx adopts a master process and multiple woker processes.
The master process is mainly responsible for collecting and distributing requests.
Whenever a request comes, the master pulls up a worker process to handle the request.
At the same time, the master process is also responsible for monitoring the status of the woker to ensure that the highly reliable woker process is generally set to be consistent with the number of CPU cores.
The number of requests that nginx's woker process can handle at the same time is only limited by memory, and can handle multiple requests.
Nginx's asynchronous non-blocking working method is taking advantage of the waiting time.
When there is a need to wait, these processes are idle and on standby, so a small number of processes can solve a large number of concurrency problems.


The concepts of synchronous, asynchronous, blocking, and non-blocking are supplemented

synchronous and asynchronous

Synchronization: When the completion of a service depends on other services, it is considered complete only after the dependent service is completed.
This is a reliable service sequence.
Either success is successful or failure is failure, and the state of the service can be kept consistent

Asynchronous: When the completion of a service depends on other services, it only notifies other dependent services to start execution without waiting for the dependent service to complete. At
this point, the service is complete. Whether the dependent service is finalized cannot be determined, so it is an unreliable sequence of services.


blocking and non-blocking

Blocking: Blocking calls mean that the current thread will be suspended before the call result is returned, waiting for message notifications, unable to perform other services, and the
function will only return after the result is obtained.

Non-blocking: The concept of non-blocking corresponds to blocking, which means that the function will not block the current thread before the result can not be obtained immediately, but will return immediately.

Interview question:
Why doesn't Nginx use multithreading?
Apache: Create multiple processes or threads,
and each process or thread will allocate CPU and memory for it
(threads are much smaller than processes, so workers support higher concurrency than perfork), and excessive concurrency will consume server resources.

Nginx: Use single thread to process requests asynchronously and non-blockingly (the administrator can configure the number of working processes of the Nginx main process) (epoll), and
will not allocate cpu and memory resources for each request, saving a lot of resources and
reducing Lots of CPU context switching. That's why Nginx supports higher concurrency.

systemctl stop firewalld
systemctl disable firewalld
setenforce 0

2. Install dependent packages
yum -y install gcc pcre-devel openssl-devel zlib-devel openssl openssl-devel

3. Create a running user and group
(the Nginx service program runs as nobody by default, it is recommended to create a special user account for it to control its access rights more accurately)
useradd -M -s /sbin/nologin nginx

4. Compile and install Nginx
cd /opt
tar zxvf nginx-1.22.0.tar.gz -C /opt/

cd nginx-1.22.0/
./configure --prefix=/usr/local/nginx \
--user=nginx \
--group=nginx \
--with-http_ssl_module \
--with-http_v2_module \
--with-http_realip_module \
--with-http_stub_status_module \
--with-http_gzip_static_module \
--with-pcre \
--with-stream \
--with-stream_ssl_module \
--with-stream_realip_module

--prefix=/usr/local/nginx specifies the installation directory of Nginx. In this case, it will be installed under the /usr/local/nginx directory.
--user=nginx and --group=nginx specify the user and group under which the Nginx process will run. In this case it will be user and group nginx.
--with-http_ssl_module enables SSL/TLS encryption support for HTTP connections.
--with-http_v2_module enables support for the HTTP2.0 protocol.
--with-http_realip_module allows Nginx to obtain the client's real IP address from the X-Real-IP or X-Forwarded-For header.
--with-http_stub_status_module enables the stub_status module, which provides a way to access Nginx status information.
--with-http_gzip_static_module Enables support for serving pre-compressed files with the .gz extension.
--with-pcre enables support for the Perl Compatible Regular Expressions (PCRE) library.
--with-stream enables support for TCP/UDP proxy modules.
--with-stream_ssl_module enables SSL/TLS encryption support for TCP/UDP connections.
--with-stream_realip_module allows Nginx to obtain the real IP address of the client from the PROXY protocol header.

make && make install

chown -R nginx.nginx /usr/local/nginx #Modify permissions

[root@localhost nginx]# ll /usr/local/nginx/
total usage 4
drwxr-xr-x. 2 nginx nginx 4096 April 11 16:18 conf
drwxr-xr-x. 2 nginx nginx 40 April 11 16: 18 html
drwxr-xr-x.2 nginx nginx 6 Apr 11 16:18 logs
drwxr-xr-x.2 nginx nginx 19 Apr 11 16:18 sbin


After installation, the functions of generating four files are as follows
1. conf: save all nginx configuration files, among which nginx.conf is the core and main configuration file of nginx server, and
other .conf are used to configure nginx related functions .For
example, the fastcgi function uses two files, fastcgi.conf and fastcgi_params.
The configuration file generally has a template configuration file, which ends with the file name .default. If you use it, copy it and remove the default.

2. The web files of the nginx server are saved in the html directory, but they can be changed to other directories to save the web files.
There is also a 50x web file that is the default error page prompt page.

3. logs: Used to save logs such as access logs and error logs of the nginx server.
The logs directory can be placed in other paths, such as /var/logs/nginx.

4. sbin: Save the nginx binary startup script, which can accept different parameters to achieve different functions

ln -s /usr/local/nginx/sbin/nginx /usr/sbin/ #Let the system recognize the operation command of nginx


nginx -t———————————Check whether the configuration file is configured correctly
nginx——————————————Start
[root@localhost opt]# killall nginx #stop


Stop
cat /usr/local/nginx/logs/nginx.pid———————————Check the PID number of nginx
kill -3 <PID number>
kill -s QUIT <PID number>
killall -3 nginx
killall - s QUIT nginx

Overload
kill -1 <PID number>
kill -s HUP <PID number> #Note here, use killall, you can use service name and PID number, but only kill can only use pid
killall -1 nginx
killall -s HUP nginx

Log separation, reopen the log file
kill -USR1 <PID number>

Smooth upgrade
kill -USR2 <PID number>


Add Nginx system service
vim /lib/systemd/system/nginx.service
[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network-online.target remote-fs .target nss-lookup.target
Wants=network-online.target
[Service]
Type=forking
PIDFile=/usr/local/nginx/run/nginx.pid
#Pay attention to the file location, if it is wrong, it will not start
ExecStart=/usr/local/ nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf 
#Pay attention to the startup file location
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s TERM $MAINPID
[Install]
WantedBy =multi-user.target

The [Unit] section describes the purpose of the unit, and where to find the documentation.
It also specifies the dependencies and order of services that need to be started before Nginx can start.

The [Service] section contains the configuration of the Nginx service, including the service type (forking in this case), the location of the PID file,
and the commands to start, reload, and stop the service.

Finally, the [Install] section specifies the target for the service installation.
ExecReload=/bin/kill -s HUP $MAINPID #equivalent to restart
ExecStop=/bin/kill -s TERM $MAINPID #equivalent to stop

mkdir -p /usr/local/nginx/run/
#Create directory

cp nginx.conf nginx.conf.bak.2023.08.04
#Backup


vim /usr/local/nginx/conf/nginx.conf
#Modify the configuration file
pid /usr/local/nginx/run/nginx.pid;
#Find the location of pid to modify  

systemctl daemon-reload 
#Reload the configuration
systemctl enable --now nginx
#Start up and start immediately if the card owner should have nginx.pid file under logs, just delete it

chown -R nginx.nginx /usr/local/nginx

systemctl start nginx.service
systemctl enable nginx.service

###Signal

The nginx command supports sending signals to it to achieve different functions

Nginx is used as a single command with the following options 
[root@node2 ~]#nginx -h
-v: Display Nginx version and exit.
-V: Display Nginx version and configuration options, then exit.
-t: Test the configuration file and exit.
-T: Test the configuration file and dump it to the console (stdout), then exit.
-q: Suppress non-error messages when testing configuration files.
-s signal: Send a signal (stop, exit, reopen, reload) to the main process.
-p prefix: Set the prefix path of Nginx (default is /etc/nginx/).
-e filename: Set the path to the error log file (default is /var/log/nginx/error.log).
-c filename: Set the path of the configuration file (default is /etc/nginx/nginx.conf).
-g directives: Set global directives without modifying configuration files.


You can use the man manual to view detailed signals. If it is not installed, go to the source package to find the man file
man path/nginx.8. If you do not add the path, you can’t open it. man help
stop SIGTERM directly stop
quit SIGQUIT Graceful exit: if someone visits, it will not end Process
reopen SIGUSR1 Split log
reload SIGHUP Reload configuration file
            SIGHUP Reload configuration, start the new worker process with a new configuration, and
                             gracefully shut down old worker processes.
             SIGQUIT Shut down gracefully. Graceful shutdown: someone is accessing and will not end the process
             SIGUSR1 Reopen log files. Re-segment log
             SIGUSR2 Upgrade the nginx executable on the fly. Run upgrade
             SIGWINCH Shut down worker processes gracefully. Gracefully shut down the worker process, the worker process is responsible for processing the request, and the request will not be closed


nginx -s stop #close nginx immediately
nginx -s reload #reload  

The -s parameter can only be used to send signals to the Nginx main process, and cannot start the nginx service

The yum installation method
centos7 needs to install the epel source
yum install -y epel-release
to install the epel source

yum install nginx -y


3. The main configuration file nginx.conf of Nginx service

#user nobody; #Run user, if not specified at compile time, the default is nobody

worker_processes 1; #The number of working processes can be configured as the number of server cores*2. If the website visits are not large, it is usually set to 1.
#error_log logs/error.log; #The location of the error log file
#pid logs/ nginx.pid; #The location of the PID file

events {     use epoll; #Use the epoll model, system kernel version 2.6 and above, it is recommended to use the epoll model to improve performance     worker_connections 1024; #Each process handles 1024 connections } #If you want to increase the number of connections for each process, you need to execute " The ulimit -n 65535" command temporarily modifies the maximum number of files that each local process can open at the same time. #On the Linux platform, when processing high-concurrency TCP connections, the highest number of concurrency is subject to the system's limit on the number of files that can be opened by a single process of the user at the same time (this is because the system must create a socket handle for each TCP connection , Each socket handle is also a file handle) #You can use the "ulimit -a" command to view the limit on the number of files that the system allows the current user process to open.





Note: After the settings are saved, you need to re-ssh to connect to see the changes in the configuration
vim /etc/security/limits.conf
# 65535 is the maximum number of open files in the Linux system
* soft nproc 65535 
* hard nproc 65535 
* soft nofile 65535 
* hard nofile 65535
reboot


Introduction to the six modules of global configuration:
global block: global configuration, which takes effect globally;
events block: configuration that affects the network connection between the Nginx server and users;

http block: configuration of most functions such as proxy, cache, log definition and third-party modules;

Server block: configure the relevant parameters of the virtual host, there can be multiple server blocks in one http block;

location block: used to configure the matching uri;
note: the content source of location matching is the URI from the web page, not the URL
(the URL represents the entire link such as: www.baidu.com/images/search, while the URI is /images/ search.
So the location of nginx matches the URI)


Four major modules of Nginx - proxy, headers, upstream, stream modules

Proxy module:
The proxy module is one of the core modules of Nginx, which is used to implement the reverse proxy function.
It allows to proxy the client's request to the backend server and return the response to the client.
The proxy module supports HTTP, HTTPS, FastCGI, uWSGI, SCGI and other protocols.
By configuring the proxy_pass directive, you can specify the proxy's backend server address.

Headers module:
The headers module is used to handle header information of HTTP requests and responses. It allows adding, modifying or deleting request headers and response headers
to achieve customized control of header information. The headers module provides a series of instructions,
such as add_header, set_header, more_set_headers, etc., for manipulating header information.

Upstream module:
The upstream module is used to configure reverse proxy server groups (also known as upstream server groups).
It defines a list of backend servers and related load balancing strategies for distributing requests to backend servers.
The upstream module configures the backend server group through the upstream block, which includes the server directive to define the backend server.

Stream module:
The stream module is Nginx's stream processing module for processing TCP and UDP traffic.
It provides TCP/UDP proxy, load balancing, data packet filtering and other functions. The stream module configures flow processing rules through the stream block, and
can forward and process traffic according to conditions such as destination address and port.

HTTP configuration

http { #File extension and file type mapping table include mime.types;

#Default file type
default_type appkgcation/octet-stream;

#Log format setting
#log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '
                         $status $body_bytes_sent "$http_referer" '
                         '"$http_user_agent" "$http_x_forwarded_for" ';
#Access log location
#access_log logs/access.log main;

#Support file sending (download)
sendfile on;

#This option allows or prohibits the use of the socket's TCP_CORK option (cache data before sending packets),
this option is only used when using sendfile
#tcp_nopush on;

#Connection keep timeout, the unit is second
#keepalive_timeout 0;
keepalive_timeout 65;

#gzip module setting, set whether to enable gzip compression output
gzip on;
------------------------------------ -------------------------------------------------- -----
Log format setting:
$remote_addr and $http_x_forwarded_for are used to record the client's ip address;
$remote_user: used to record the client user name;
$time_local: used to record the access time and time zone;
$request: used to record Record the url and http protocol of the request;
$status: used to record the status of the request; success is 200,
$body_bytes_sent: record the size of the body content of the file sent to the client;
$http_referer: used to record which page link is accessed from;
$http_user_agent : Record the relevant information of the customer's browser;
usually the web server is placed behind the reverse proxy, so that the customer's IP address cannot be obtained, and the
IP address obtained through $remote_add is the IP address of the reverse proxy server.
The reverse proxy server can add x_forwarded_for information in the http header information of the forwarding request
to record the IP address of the original client and the address of the server requested by the original client.
-------------------------------------------------- ------------------------------------------
# Web service monitoring configuration
server {    #Listening address and port    listen 80;    #Site domain name, there can be more than one, separated by spaces    server name www.kgc.com;    #Webpage default character set    charset utf-8;    #root Directory configuration    location / {    The location of the root directory of the website /usr/local/nginx/html    root html;    #Internal error feedback page    error_page 500 502 503 504 /50x.html;    #Error page configuration    location = /50x.html {    root html ;    }   }  } vim /usr/local/nginx/conf/nginx.conf  server {         listen 80;         server_name www.kgc.com; systemctl restart nginx.service        


















 




        

echo "192.168.233.21 www.kgc.com" > /etc/hosts --- No forward analysis, direct host mapping
Access browser
 
location common configuration instructions, root, alias, proxy_pass (reverse proxy configuration)

Nginx sets the virtual directory through alias. In the configuration of nginx, there is a difference between the alias directory and the root directory:

1) The directory specified by alias is accurate, that is, the files in the path directory accessed by location matching are directly searched in the alias directory;

2) The directory specified by root is the upper-level directory of the path directory accessed by location matching. This path directory must actually exist under the directory specified by root;

3) The rewrite break cannot be used in the directory block using the alias label (the specific reason is unknown); in addition, the "/" symbol must be added after the directory specified by the alias! !

4) In the alias virtual directory configuration, if the path directory matching the location does not have "/" behind it, then adding "/" after the path directory in the accessed url address does not affect access, and it will automatically add "/" when accessing ";
but if "/" is added after the path directory matched by the location, then "/" must be added to the path directory in the accessed url address, and "/" will not be automatically added when accessing. If you do not add "/", access will fail!
    
5) In the root directory configuration, the path directory matched by location with or without "/" after it will not affect access.

Other differences:
1. alias can only be used in location, while root can exist in server, http and location.
2. "/" must be used at the end of alias, otherwise the file will not be found, and root is dispensable to "/".

Access status statistics configuration
1. First use the command /usr/local/nginx/sbin/nginx -V to check whether the installed Nginx contains the HTTP_STUB_STATUS module 2.
Modify the nginx.conf configuration file, specify the access location and add the stub_status configuration

vim /usr/local/nginx/conf/nginx.conf
......
http { ......     server {         listen 80;         server_name www.kgc.com;         charset utf-8;         location / {             root html;             index index.html index.php;         }         ##Add stub_status configuration##         location /status { #The access location is /status             stub_status on; #Open the status statistics function             access_log off; #Close the log record of this location         }     } } systemctl restart nginx
















http://192.168.233.21/status
Active connections: 1 
server accepts handled requests
 90 90 90 
Reading: 0 Writing: 1 Waiting: 0 

Active connections: indicates the current number of active connections;
server accepts handled requests: indicates the connection information that has been processed, and
the three numbers indicate the number of connections processed, the number of successful TCP handshakes, and the number of requests processed in turn.

Authorization-based access control
1. Generate user password authentication file
yum install -y httpd-tools----httpasswd is a tool, first install
htpasswd -c /usr/local/nginx/passwd.db zhangsan Create a user, passwd. db stores user information
chown nginx /usr/local/nginx/passwd.db only root and nginx users can read
chmod 400 /usr/local/nginx/passwd.db

vim /usr/local/nginx/conf/nginx.conf
......
    server {         location / {             ......             ##Add authentication configuration##             auth_basic "secret";             auth_basic_user_file /usr/local/nginx/ passwd.db;         }     } nginx -t systemctl restart nginx client-based access control The access control rules are as follows: deny IP/IP segment: Deny client access of a certain IP or IP segment. allow IP/IP segment: allow the client of a certain IP or IP segment to access. The rules are executed from top to bottom, and stop if they match, and do not match down.









    




vim /usr/local/nginx/conf/nginx.conf
......
    server {         location / {             ......             ##Add control rules##             deny 192.168.233.21; #Deny access client IP             allow all; #Allow other IP clients to access         }     } systemctl restart nginx







Nginx virtual host based on domain name

Provide domain name resolution for virtual host
echo "192.168.233.21 www.kgc.com www.accp.com" >> /etc/hosts

Prepare web documentation for virtual hosting
mkdir -p /var/www/html/kgc
mkdir -p /var/www/html/accp
echo "<h1>www.kgc.com</h1>" > /var/www/html /kgc/index.html
echo "<h1>www.accp.com</h1>" > /var/www/html/accp/index.html

Modify the Nginx configuration file
vim /usr/local/nginx/conf/nginx.conf
......
http { ......     server {         listen 80;         server_name www.kgc.com; #Set the domain name www.kgc .com         charset utf-8;         access_log logs/www.kgc.access.log;          location / {             root /var/www/html/kgc; #Set the working directory             index of www.kgc.com index.html index.php;         }         error_page 500 502 503 504 /50x.html;         location = 50x.html{             root html;         }     }     server {         listen 80;















    


        server_name www.accp.com;                    #设置域名www.accp.com
        charset utf-8;
        access_log logs/www.accp.access.log; 
        location / {
            root /var/www/html/accp;
            index index.html index.php;
        }
        error_page 500 502 503 504 /50x.html;
        location = 50x.html{
            root html;
        }
    }    
}

IP-based Nginx virtual host:
ifconfig ens33:0 192.168.233.100 netmask 255.255.255.0 

vim /usr/local/nginx/conf/nginx.conf
......
http { ...... server {         listen 192.168.233.21:80; #Set listening address         server_name www.kgc.com;         charset utf- 8;         access_log logs/www.kgc.access.log;          location / {             root /var/www/html/kgc;             index index.html index.php;         }         error_page 500 502 503 504 /50x.html;         location = 50x.html {             root html;         }     }














server {
    listen 192.168.233.33:80;                    #设置监听地址
    server_name www.accp.com;
    charset utf-8;
    access_log logs/www.accp.access.log; 
    location / {
        root /var/www/html/accp;
        index index.html index.php;
    }
    error_page 500 502 503 504 /50x.html;
    location = 50x.html{
        root html;
    }
}    
}
systemctl restart nginx

Port-based Nginx virtual host:
vim /usr/local/nginx/conf/nginx.conf
......
http { ......     server {         listen 192.168.233.21:8080; #Set listening port 8080         server_name www .kgc.com;         charset utf-8;         access_log logs/www.kgc.access.log;          location / {             root /var/www/html/kgc;             index index.html index.php;         }         error_page 500 502 503 504 /50x .html;         location = 50x.html{             root html;         }     }














server {
    listen 192.168.233.21:8888;                    #设置监听 8888 端口
    server_name www.accp.com;
    charset utf-8;
    access_log logs/www.accp.access.log; 
    location / {
        root /var/www/html/accp;
        index index.html index.php;
    }
    error_page 500 502 503 504 /50x.html;
    location = 50x.html{
        root html;
    }
}    
systemctl restart nginx

Smooth upgrade:
1. After dragging in 1.22.0, compile and install./configure
--prefix=/usr/local/nginx \
--user=nginx \
--group=nginx \
--with-http_ssl_module \
--with -http_v2_module \
--with-http_realip_module \
--with-http_stub_status_module \
--with-http_gzip_static_module \
--with-pcre \
--with-stream \
--with-stream_ssl_module \
--with-stream_realip_module
Note: The installation location and The previous version is the same. Second, just make after the compilation is complete, do not use make install

2. In the old version directory, rename the original execution file
[root@localhost sbin]# mv nginx nginx.bak

3. [root@localhost nginx-1.22.0]#cp objs/nginx /apps/nginx/sbin/ #Copy the
new version into it

4. [root@localhost sbin]# kill -USR2 `cat /usr/local/nginx/run/nginx.pid`
#Under the old version, transmit signals and upgrade smoothly

[root@localhost sbin]# ps auxf|grep nginx 
root      16386  0.0  0.0 112824   988 pts/3    S+   14:35   0:00          \_ grep --color=auto ngin
root       5479  0.0  0.1  46368  2044 ?        Ss   13:15   0:00 nginx: master process /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
nginx      5489  0.0  0.1  48888  2092 ?        S    13:16   0:00  \_ nginx: worker process
nginx      5490  0.0  0.1  48888  2080 ?        S    13:16   0:00  \_ nginx: worker process
root      16382  0.0  0.1  46224  3364 ?        S    14:35   0:00  \_ nginx: master process /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
nginx     16383  0.0  0.0  48760  1972 ?        S    14:35   0:00      \_ nginx: worker process
nginx     16384  0.0  0.0  48760  1984 ?        S    14:35   0:00      \_ nginx: worker process


5、[root@localhost run]# kill -WINCH `cat /usr/local/nginx/run/nginx.pid.oldbin`
[root@localhost run]# ps auxf|grep nginx
root      16490  0.0  0.0 112824   984 pts/3    S+   14:43   0:00          \_ grep --color=auto ngin
root       5479  0.0  0.1  46368  2044 ?        Ss   13:15   0:00 nginx: master process /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
root      16382  0.0  0.1  46224  3364 ?        S    14:35   0:00  \_ nginx: master process /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
nginx     16383  0.0  0.0  48760  1972 ?        S    14:35   0:00      \_ nginx: worker process
nginx     16384  0.0  0.0  48760  1984 ?        S    14:35   0:00      \_ nginx: worker process

Exit the old process gracefully, and the upgrade ends;

回滚:
[root@localhost opt]# kill -HUP `cat /apps/nginx/run/nginx.pid.oldbin`
检查进程:
[root@localhost objs]# ps -ef | grep nginx
root       5479      1  0 13:15 ?        00:00:00 nginx: master process /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
root      16382   5479  0 14:35 ?        00:00:00 nginx: master process /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
nginx     16383  16382  0 14:35 ?        00:00:00 nginx: worker process
nginx     16384  16382  0 14:35 ?        00:00:00 nginx: worker process
nginx     16728   5479  0 15:05 ?        00:00:00 nginx: worker process
nginx     16729   5479  0 15:05 ?        00:00:00 nginx: worker process
root 16740 13113 0 15:06 pts/2 00:00:00 grep --color=auto nginx
is two processes

[root@localhost objs]# kill -QUIT `cat /usr/local/nginx/run/nginx.pid`
gracefully stops the Nginx web server by sending an exit signal to the main process. complete rollback

Guess you like

Origin blog.csdn.net/ZWH9991/article/details/132291107