NGINX概念以及部署搭建

NGINX概念以及搭建

NGINX概述

Nginx (engine x) 是一个高性能的HTTP和反向代理web服务器 ,同时也提供了IMAP/POP3/SMTP服务。Nginx是由伊戈尔·赛索耶夫为俄罗斯访问量第二的Rambler.ru站点(俄文:Рамблер)开发的,公开版本1.19.6发布于2020年12月15日。

其将源代码以类BSD许可证的形式发布,因它的稳定性、丰富的功能集、简单的配置文件和低系统资源的消耗而闻名。2022年01月25日,nginx 1.21.6发布。

Nginx是一款轻量级的Web 服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,在BSD-like 协议下发行。其特点是占有内存少,并发能力强,事实上nginx的并发能力在同类型的网页服务器中表现较好。

NGINX功能介绍

  • 静态的web资源服务器html,图片,js,css,txt等静态资源
  • http/https协议的反向代理
  • 结合FastCGI/uWSGI/SCGI等协议反向代理动态资源请求
  • tcp/udp协议的请求转发(反向代理)
  • imap4/pop3协议的反向代理

NGINX基础特性

  • 模块化设计,较好的扩展性
  • 高可靠性
  • 支持热部署:不停机更新配置文件,升级版本,更换日志文件
  • 低内存消耗:10000个keep-alive连接模式下的非活动连接,仅需2.5M内存
  • event-driven,aio,mmap,sendfile

Web服务相关的功能

  • 虚拟主机(server)
  • 支持 keep-alive 和管道连接(利用一个连接做多次请求)
  • 访问日志(支持基于日志缓冲提高其性能)
  • url rewirte
  • 路径别名
  • 基于IP及用户的访问控制
  • 支持速率限制及并发数限制
  • 重新配置和在线升级而无须中断客户的工作进程

NGINX架构

在这里插入图片描述

NGINX进程结构

web请求处理机制

  • 多进程方式:服务器每接收到一个客户端请求就有服务器的主进程生成一个子进程响应客户端,直到用户关闭连接,这样的优势是处理速度快,子进程之间相互独立,但是如果访问过大会导致服务器资源耗尽而无法提供请求。

  • 多线程方式:与多进程方式类似,但是每收到一个客户端请求会有服务进程派生出一个线程来个客户方进行交互,一个线程的开销远远小于一个进程,因此多线程方式在很大程度减轻了web服务器对系统资源的要求,但是多线程也有自己的缺点,即当多个线程位于同一个进程内工作的时候,可以相互访问同样的内存地址空间,所以他们相互影响,一旦主进程挂掉则所有子线程都不能工作了,IIS服务器使用了多线程的方式,需要间隔一段时间就重启一次才能稳定。

NGINX模块

  • 核心模块:是 Nginx 服务器正常运行必不可少的模块,提供错误日志记录 、配置文件解析 、事件驱动机制 、进程管理等核心功能
  • 标准HTTP模块:提供 HTTP 协议解析相关的功能,比如: 端口配置 、 网页编码设置 、 HTTP响应头设置 等等
  • 可选HTTP模块:主要用于扩展标准的 HTTP 功能,让 Nginx 能处理一些特殊的服务,比如:
  • Flash 多媒体传输 、解析 GeoIP 请求、 网络传输压缩 、 安全协议 SSL 支持等
  • 邮件服务模块:主要用于支持 Nginx 的 邮件服务 ,包括对 POP3 协议、 IMAP 协议和 SMTP协议的支持
  • Stream服务模块: 实现反向代理功能,包括TCP协议代理
  • 第三方模块:是为了扩展 Nginx 服务器应用,完成开发者自定义功能,比如: Json 支持、 Lua 支持等

nginx高度模块化,但其模块早期不支持DSO机制;1.9.11 版本支持动态装载和卸载

核心模块:core module
标准模块:
 HTTP 模块: ngx_http_*
 HTTP Core modules   #默认功能
 HTTP Optional modules #需编译时指定
 Mail 模块: ngx_mail_*
 Stream 模块 ngx_stream_*
第三方模块

在这里插入图片描述

如何搭建NGINX

NGINX官网(盈利组织):https://www.nginx.com/
NGINX官网(非盈利组织):https://nginx.org/en/download.html

CentOS7默认无NGINX,yum官方源没有NGINX安装包

[root@localhost ~]# yum info nginx  #检测光盘中是否可安装nginx软件包
已加载插件:fastestmirror, langpacks
base                                                   | 3.6 kB     00:00     
extras                                                 | 2.9 kB     00:00     
updates                                                | 2.9 kB     00:00     
(1/4): base/7/x86_64/group_gz                            | 153 kB   00:00     
(2/4): extras/7/x86_64/primary_db                        | 249 kB   00:00     
(3/4): base/7/x86_64/primary_db                          | 6.1 MB   00:01     
(4/4): updates/7/x86_64/primary_db                       |  20 MB   00:03     
Determining fastest mirrors
 * base: mirrors.aliyun.com
 * extras: mirrors.aliyun.com
 * updates: mirrors.aliyun.com
错误:没有匹配的软件包可以列出

方法一:安装epel源,让NGINX软件包可安装

第一台虚拟机:20.0.0.100使用epel源来搭建NGINX

[root@localhost ~]# yum install epel-release.noarch -y
已加载插件:fastestmirror, langpacks
Loading mirror speeds from cached hostfile
 * base: mirrors.aliyun.com
 * extras: mirrors.aliyun.com
 * updates: mirrors.aliyun.com
正在解决依赖关系
--> 正在检查事务
---> 软件包 epel-release.noarch.0.7-11 将被 安装
--> 解决依赖关系完成

依赖关系解决

==============================================================================
 Package               架构            版本             源               大小
==============================================================================
正在安装:
 epel-release          noarch          7-11             extras           15 k

事务概要
==============================================================================
安装  1 软件包

总下载量:15 k
安装大小:24 k
Downloading packages:
警告:/var/cache/yum/x86_64/7/extras/packages/epel-release-7-11.noarch.rpm: 头V3 RSA/SHA256 Signature, 密钥 ID f4a80eb5: NOKEY
epel-release-7-11.noarch.rpm 的公钥尚未安装
epel-release-7-11.noarch.rpm                             |  15 kB   00:00     
从 file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7 检索密钥
导入 GPG key 0xF4A80EB5:
 用户ID     : "CentOS-7 Key (CentOS 7 Official Signing Key) <security@centos.org>"
 指纹       : 6341 ab27 53d7 8a78 a7c2 7bb1 24c6 a8a7 f4a8 0eb5
 软件包     : centos-release-7-4.1708.el7.centos.x86_64 (@anaconda)
 来自       : /etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  正在安装    : epel-release-7-11.noarch                                  1/1 
  验证中      : epel-release-7-11.noarch                                  1/1 

已安装:
  epel-release.noarch 0:7-11                                                  

完毕!

官网下载安装包

[root@localhost ~]# wget http://nginx.org/download/nginx-1.18.0.tar.gz
--2023-03-10 11:46:18--  http://nginx.org/download/nginx-1.18.0.tar.gz
正在解析主机 nginx.org (nginx.org)... 3.125.197.172, 52.58.199.22, 2a05:d014:edb:5702::6, ...
正在连接 nginx.org (nginx.org)|3.125.197.172|:80... 已连接。
已发出 HTTP 请求,正在等待回应... 200 OK
长度:1039530 (1015K) [application/octet-stream]
正在保存至: “nginx-1.18.0.tar.gz”

100%[====================================>] 1,039,530    191KB/s 用时 5.6s   

2023-03-10 11:46:24 (182 KB/s) - 已保存 “nginx-1.18.0.tar.gz” [1039530/1039530])

[root@localhost ~]# ls
anaconda-ks.cfg       nginx-1.18.0.tar.gz  模板  图片  下载  桌面
initial-setup-ks.cfg  公共                 视频  文档  音乐

在这里插入图片描述

再次检测是否可安装NGINX软件包

[root@localhost ~]# cp nginx-1.18.0.tar.gz /opt/
[root@localhost ~]# cd /opt/
[root@localhost opt]# ls
nginx-1.18.0.tar.gz  rh
[root@localhost opt]# yum info nginx  
已加载插件:fastestmirror, langpacks
epel/x86_64/metalink                                   | 7.8 kB     00:00     
epel                                                   | 4.7 kB     00:00     
(1/3): epel/x86_64/group_gz                              |  99 kB   00:00     
(2/3): epel/x86_64/updateinfo                            | 1.0 MB   00:00     
(3/3): epel/x86_64/primary_db                            | 7.0 MB   00:01     
Loading mirror speeds from cached hostfile
 * base: mirrors.aliyun.com
 * epel: mirrors.bfsu.edu.cn
 * extras: mirrors.aliyun.com
 * updates: mirrors.aliyun.com
可安装的软件包
名称    :nginx
架构    :x86_64
时期       :1
版本    :1.20.1
发布    :10.el7
大小    :588 k
源    :epel/x86_64
简介    : A high performance web server and reverse proxy server
网址    :https://nginx.org
协议    : BSD
描述    : Nginx is a web server and a reverse proxy server for HTTP, SMTP,
         : POP3 and IMAP protocols, with a strong focus on high concurrency,
         : performance and low memory usage.

下载安装NGINX软件包,并启动

[root@localhost opt]# yum install nginx -y
已加载插件:fastestmirror, langpacks
Loading mirror speeds from cached hostfile
 * base: mirrors.aliyun.com
 * epel: mirrors.bfsu.edu.cn
 * extras: mirrors.aliyun.com
 * updates: mirrors.aliyun.com
正在解决依赖关系
--> 正在检查事务
---> 软件包 nginx.x86_64.1.1.20.1-10.el7 将被 安装
--> 正在处理依赖关系 nginx-filesystem = 1:1.20.1-10.el7,它被软件包 1:nginx-1.20.1-10.el7.x86_64 需要
--> 正在处理依赖关系 libcrypto.so.1.1(OPENSSL_1_1_0)(64bit),它被软件包 1:nginx-1.20.1-10.el7.x86_64 需要
--> 正在处理依赖关系 libssl.so.1.1(OPENSSL_1_1_0)(64bit),它被软件包 1:nginx-1.20.1-10.el7.x86_64 需要
--> 正在处理依赖关系 libssl.so.1.1(OPENSSL_1_1_1)(64bit),它被软件包 1:nginx-1.20.1-10.el7.x86_64 需要
--> 正在处理依赖关系 nginx-filesystem,它被软件包 1:nginx-1.20.1-10.el7.x86_64 需要
--> 正在处理依赖关系 libcrypto.so.1.1()(64bit),它被软件包 1:nginx-1.20.1-10.el7.x86_64 需要
--> 正在处理依赖关系 libssl.so.1.1()(64bit),它被软件包 1:nginx-1.20.1-10.el7.x86_64 需要
--> 正在检查事务
---> 软件包 nginx-filesystem.noarch.1.1.20.1-10.el7 将被 安装
---> 软件包 openssl11-libs.x86_64.1.1.1.1k-5.el7 将被 安装
--> 解决依赖关系完成

依赖关系解决

==============================================================================
 Package                架构         版本                    源          大小
==============================================================================
正在安装:
 nginx                  x86_64       1:1.20.1-10.el7         epel       588 k
为依赖而安装:
 nginx-filesystem       noarch       1:1.20.1-10.el7         epel        24 k
 openssl11-libs         x86_64       1:1.1.1k-5.el7          epel       1.5 M

事务概要
==============================================================================
安装  1 软件包 (+2 依赖软件包)

总下载量:2.1 M
安装大小:5.3 M
Downloading packages:
警告:/var/cache/yum/x86_64/7/epel/packages/nginx-1.20.1-10.el7.x86_64.rpm: 头V4 RSA/SHA256 Signature, 密钥 ID 352c64e5: NOKEY
nginx-1.20.1-10.el7.x86_64.rpm 的公钥尚未安装
(1/3): nginx-1.20.1-10.el7.x86_64.rpm                    | 588 kB   00:00     
(2/3): nginx-filesystem-1.20.1-10.el7.noarch.rpm         |  24 kB   00:00     
(3/3): openssl11-libs-1.1.1k-5.el7.x86_64.rpm            | 1.5 MB   00:00     
------------------------------------------------------------------------------
总计                                             2.7 MB/s | 2.1 MB  00:00     
从 file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7 检索密钥
导入 GPG key 0x352C64E5:
 用户ID     : "Fedora EPEL (7) <epel@fedoraproject.org>"
 指纹       : 91e9 7d7c 4a5e 96f1 7f3e 888f 6a2f aea2 352c 64e5
 软件包     : epel-release-7-11.noarch (@extras)
 来自       : /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  正在安装    : 1:openssl11-libs-1.1.1k-5.el7.x86_64                      1/3 
  正在安装    : 1:nginx-filesystem-1.20.1-10.el7.noarch                   2/3 
  正在安装    : 1:nginx-1.20.1-10.el7.x86_64                              3/3 
  验证中      : 1:nginx-filesystem-1.20.1-10.el7.noarch                   1/3 
  验证中      : 1:nginx-1.20.1-10.el7.x86_64                              2/3 
  验证中      : 1:openssl11-libs-1.1.1k-5.el7.x86_64                      3/3 

已安装:
  nginx.x86_64 1:1.20.1-10.el7                                                

作为依赖被安装:
  nginx-filesystem.noarch 1:1.20.1-10.el7                                     
  openssl11-libs.x86_64 1:1.1.1k-5.el7                                        

完毕!
[root@localhost opt]# systemctl start nginx  ## 启动nginx

命令:信号 nginx -h

nginx 命令支持向其发送信号,实现不同功能

nginx 当做单独命令使用有以下选项

[root@localhost nginx-1.18.0]# nginx -h
nginx version: nginx/1.20.1
Usage: nginx [-?hvVtTq] [-s signal] [-p prefix]
             [-e filename] [-c filename] [-g directives]

Options:
  -?,-h         : this help
  -v            : show version and exit
  -V            : show version and configure options then exit
  -t            : test configuration and exit
  -T            : test configuration, dump it and exit
  -q            : suppress non-error messages during configuration testing
  -s signal     : send signal to a master process: stop, quit, reopen, reload
  -p prefix     : set prefix path (default: /usr/share/nginx/)
  -e filename   : set error log file (default: /var/log/nginx/error.log)
  -c filename   : set configuration file (default: /etc/nginx/nginx.conf)
  -g directives : set global directives out of configuration file

命令:查看NGINX进程 ps aux |grep nginx

[root@localhost opt]# ps aux |grep nginx
root      39486  0.0  0.0  41412   944 ?        Ss   13:38   0:00 nginx: master process /usr/sbin/nginx
nginx     39487  0.0  0.0  43884  1960 ?        S    13:38   0:00 nginx: worker process
nginx     39488  0.0  0.0  43884  1960 ?        S    13:38   0:00 nginx: worker process
root      39528  0.0  0.0 112676   980 pts/0    S+   13:41   0:00 grep --color=auto nginx

在这里插入图片描述

命令:查看NGINX版本 nginx -v

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

命令:查看NGINX编译信息 nginx -V

[root@localhost opt]# nginx -V
nginx version: nginx/1.20.1
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC) 
built with OpenSSL 1.1.1k  FIPS 25 Mar 2021
TLS SNI support enabled
configure arguments: --prefix=/usr/share/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --http-client-body-temp-path=/var/lib/nginx/tmp/client_body --http-proxy-temp-path=/var/lib/nginx/tmp/proxy --http-fastcgi-temp-path=/var/lib/nginx/tmp/fastcgi --http-uwsgi-temp-path=/var/lib/nginx/tmp/uwsgi --http-scgi-temp-path=/var/lib/nginx/tmp/scgi --pid-path=/run/nginx.pid --lock-path=/run/lock/subsys/nginx --user=nginx --group=nginx --with-compat --with-debug --with-file-aio --with-google_perftools_module --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_degradation_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_image_filter_module=dynamic --with-http_mp4_module --with-http_perl_module=dynamic --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-http_xslt_module=dynamic --with-mail=dynamic --with-mail_ssl_module --with-pcre --with-pcre-jit --with-stream=dynamic --with-stream_ssl_module --with-stream_ssl_preread_module --with-threads --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -m64 -mtune=generic' --with-ld-opt='-Wl,-z,relro -specs=/usr/lib/rpm/redhat/redhat-hardened-ld -Wl,-E'

命令:发送信号来执行命令 nginx -s

[root@localhost opt]# nginx -s stop  
[root@localhost opt]# ps aux |grep nginx
root      40373  0.0  0.0 112676   980 pts/0    R+   15:39   0:00 grep --color=auto nginx

在这里插入图片描述
nginx -s stop #立即关闭nginx
nginx -s quit #优雅退出 不影响业务的状态下退出
nginx -s reload #重新加载
nginx -g 指定配置,不已配置文件中的为准

kill -L    看信号大全
nginx -h   中可以看到的信号较少
s signal     : send signal to a master process: stop, quit, reopen, reload

可以使用man手册来查看详细的信号 如果没安装,去源码包里找到man文件
man   路径/nginx.8      不加路径打不开man帮助
stop      	SIGTERM        直接停止
quit       	SIGQUIT        优雅的退出:有人在访问不会结束进程
reopen   	SIGUSR1        分割日志
reload   	SIGHUP         重新加载配置文件
			SIGHUP           Reload configuration, start the new worker process with a new configuration, and
                             gracefully shut down old worker processes.
     		SIGQUIT          Shut down gracefully.  优雅的关闭:有人在访问不会结束进程
     		SIGUSR1          Reopen log files.       重新分割日志
     		SIGUSR2          Upgrade the nginx executable on the fly.  运行中升级
     		SIGWINCH         Shut down worker processes gracefully.    优雅的关闭worker进程,work进程负责处理请求,还有请求不会关闭
信号含义
kill杀死进程,即强制结束进程
INT表示结束进程,但并不是强制性的,常用的"CtrI+C"组合键发出就是一个kill-2的信号
QUIT从容关闭,退出
TERM正常结束进程,是kill命令的默认信号
HUP重载配置用新的配置开始新的工作进程从容关闭旧的工作进程
USR1重新打开日志文件
USR2平滑升级可执行程序
WINCH从容关闭工作进程
SEGV段错误

在这里插入图片描述

命令:检查语法 nginx -t

[root@localhost opt]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

命令:指定配置,不已配置文件中的为准 nginx -g

[root@localhost nginx]# systemctl stop nginx
[root@localhost nginx]# vim /etc/nginx/nginx.conf

将配置文件中的注释掉
在这里插入图片描述

[root@localhost nginx]# id zhangsan
uid=1000(zhangsan) gid=1000(zhangsan)=1000(zhangsan)
[root@localhost nginx]# nginx -g "user zhangsan;"
[root@localhost nginx]# ps aux |grep nginx
root      41323  0.0  0.0  41412   956 ?        Ss   20:06   0:00 nginx: master process nginx -g user zhangsan;
zhangsan       41324  0.0  0.0  43884  1976 ?        S    20:06   0:00 nginx: worker process
zhangsan       41325  0.0  0.0  43884  1976 ?        S    20:06   0:00 nginx: worker process
root      41333  0.0  0.0 112676   980 pts/0    S+   20:06   0:00 grep --color=auto nginx

命令:前台运行,在Dock容器中会用到 nginx -g “daemon off;”

[root@localhost nginx]# nginx -s stop
[root@localhost nginx]# nginx -g "daemon off;"
[root@localhost ~]# ss -ntap |grep 80
LISTEN     0      128          *:80                       *:*                   users:(("nginx",pid=41471,fd=6),("nginx",pid=41470,fd=6),("nginx",pid=41469,fd=6))
TIME-WAIT  0      0      20.0.0.100:34918              34.107.221.82:80                 
LISTEN     0      128         :::80                      :::*                   users:(("nginx",pid=41471,fd=7),("nginx",pid=41470,fd=7),("nginx",pid=41469,fd=7))

在这里插入图片描述

方法二:需要下NGINX最新的软件包,到NGINX官网(非盈利组织):https://nginx.org/en/download.html

第二台虚拟机:20.0.0.200使用官方安装环境来搭建NGINX

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true

下载安装NGINX软件包,并启动NGINX

[root@localhost ~]# yum install nginx
已加载插件:fastestmirror, langpacks
Loading mirror speeds from cached hostfile
 * base: mirrors.ustc.edu.cn
 * extras: mirrors.ustc.edu.cn
 * updates: mirrors.ustc.edu.cn
没有可用软件包 nginx。
错误:无须任何处理
[root@localhost ~]# cd /etc/yum.repos.d/
[root@localhost yum.repos.d]# ls
CentOS-Base.repo       CentOS-fasttrack.repo  CentOS-Vault.repo
CentOS-CR.repo         CentOS-Media.repo
CentOS-Debuginfo.repo  CentOS-Sources.repo
[root@localhost yum.repos.d]# vim nginx.repo
############ 按a键切入编辑模式 #################
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true
############ 按esc键,:wq保存退出  #################

[root@localhost yum.repos.d]# yum install nginx -y
已加载插件:fastestmirror, langpacks
nginx-stable                                           | 2.9 kB     00:00     
nginx-stable/7/x86_64/primary_db                         |  81 kB   00:00     
Loading mirror speeds from cached hostfile
 * base: mirrors.ustc.edu.cn
 * extras: mirrors.ustc.edu.cn
 * updates: mirrors.ustc.edu.cn
正在解决依赖关系
--> 正在检查事务
---> 软件包 nginx.x86_64.1.1.22.1-1.el7.ngx 将被 安装
--> 解决依赖关系完成

依赖关系解决

==============================================================================
 Package     架构         版本                       源                  大小
==============================================================================
正在安装:
 nginx       x86_64       1:1.22.1-1.el7.ngx         nginx-stable       797 k

事务概要
==============================================================================
安装  1 软件包

总下载量:797 k
安装大小:2.8 M
Downloading packages:
警告:/var/cache/yum/x86_64/7/nginx-stable/packages/nginx-1.22.1-1.el7.ngx.x86_64.rpm: 头V4 RSA/SHA256 Signature, 密钥 ID 7bd9bf62: NOKEY
nginx-1.22.1-1.el7.ngx.x86_64.rpm 的公钥尚未安装
nginx-1.22.1-1.el7.ngx.x86_64.rpm                        | 797 kB   00:02     
从 https://nginx.org/keys/nginx_signing.key 检索密钥
导入 GPG key 0x7BD9BF62:
 用户ID     : "nginx signing key <signing-key@nginx.com>"
 指纹       : 573b fd6b 3d8f bc64 1079 a6ab abf5 bd82 7bd9 bf62
 来自       : https://nginx.org/keys/nginx_signing.key
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  正在安装    : 1:nginx-1.22.1-1.el7.ngx.x86_64                           1/1 
----------------------------------------------------------------------

Thanks for using nginx!

Please find the official documentation for nginx here:
* https://nginx.org/en/docs/

Please subscribe to nginx-announce mailing list to get
the most important news about nginx:
* https://nginx.org/en/support.html

Commercial subscriptions for nginx are available on:
* https://nginx.com/products/

----------------------------------------------------------------------
  验证中      : 1:nginx-1.22.1-1.el7.ngx.x86_64                           1/1 

已安装:
  nginx.x86_64 1:1.22.1-1.el7.ngx                                             

完毕!
[root@localhost yum.repos.d]# systemctl start nginx   #启动nginx

输入本地ip地址,可查看页面
在这里插入图片描述

命令:使用kill -USR1 [进程](用ps aux |grep nginx查看进程,第一个root进程数)实现NGINX日志分割

[root@localhost opt]# cd /var/log/nginx
[root@localhost nginx]# ls
access.log  error.log
[root@localhost nginx]# mv access.log access.log.bak
[root@localhost nginx]# ls
access.log.bak  error.log
[root@localhost nginx]# touch access.log
[root@localhost nginx]# ls
access.log  access.log.bak  error.log
[root@localhost nginx]# cat access.log.bak
20.0.0.100 - - [10/Mar/2023:14:39:47 +0800] "GET / HTTP/1.1" 200 4833 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0" "-"
20.0.0.100 - - [10/Mar/2023:14:39:47 +0800] "GET /img/centos-logo.png HTTP/1.1" 200 3030 "http://20.0.0.100/" "Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0" "-"
20.0.0.100 - - [10/Mar/2023:14:39:47 +0800] "GET /img/html-background.png HTTP/1.1" 200 1801 "http://20.0.0.100/" "Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0" "-"
20.0.0.100 - - [10/Mar/2023:14:39:47 +0800] "GET /img/header-background.png HTTP/1.1" 200 82896 "http://20.0.0.100/" "Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0" "-"
20.0.0.100 - - [10/Mar/2023:14:39:47 +0800] "GET /favicon.ico HTTP/1.1" 404 3650 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0" "-"
20.0.0.100 - - [10/Mar/2023:14:39:47 +0800] "GET /favicon.ico HTTP/1.1" 404 3650 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0" "-"
[root@localhost nginx]# ps aux |grep nginx
root      39486  0.0  0.0  41412   944 ?        Ss   19:02   0:00 nginx: master process /usr/sbin/nginx
nginx     39487  0.0  0.0  43884  1960 ?        S    19:02   0:00 nginx: worker process
nginx     39488  0.0  0.1  43884  2456 ?        S    19:02   0:00 nginx: worker process
root      40843  0.0  0.0 112676   980 pts/0    S+   19:35   0:00 grep --color=auto nginx
[root@localhost nginx]# kill -USR1 39486

刷新网页表示当用户进入网页中日志表中会记录信息
在这里插入图片描述

[root@localhost nginx]# cat access.log
20.0.0.100 - - [10/Mar/2023:19:36:49 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0" "-"
20.0.0.100 - - [10/Mar/2023:19:36:49 +0800] "GET /img/html-background.png HTTP/1.1" 304 0 "http://20.0.0.100/" "Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0" "-"
20.0.0.100 - - [10/Mar/2023:19:36:49 +0800] "GET /img/header-background.png HTTP/1.1" 304 0 "http://20.0.0.100/" "Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0" "-"
20.0.0.100 - - [10/Mar/2023:19:36:49 +0800] "GET /img/centos-logo.png HTTP/1.1" 304 0 "http://20.0.0.100/" "Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0" "-"
20.0.0.100 - - [10/Mar/2023:19:38:39 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0" "-"
20.0.0.100 - - [10/Mar/2023:19:38:39 +0800] "GET /img/html-background.png HTTP/1.1" 304 0 "http://20.0.0.100/" "Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0" "-"
20.0.0.100 - - [10/Mar/2023:19:38:39 +0800] "GET /img/centos-logo.png HTTP/1.1" 304 0 "http://20.0.0.100/" "Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0" "-"
20.0.0.100 - - [10/Mar/2023:19:38:39 +0800] "GET /img/header-background.png HTTP/1.1" 304 0 "http://20.0.0.100/" "Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0" "-"

使用方法二:官网 编译安装NGINX(使用上面的20.0.0.200虚拟机继续完成操作)

[root@localhost ~]# yum -y install gcc pcre-devel openssl-devel zlib-devel #安装依赖包

[root@localhost ~]# 
[root@localhost nginx]# useradd -M -s /sbin/nologin nginx
useradd:用户“nginx”已存在
  #新建nginx用户便于管理

[root@localhost ~]# cd /opt/
[root@localhost opt]# wget http://nginx.org/download/nginx-1.18.0.tar.gz  #官网下载安装包
--2023-03-11 01:44:16--  http://nginx.org/download/nginx-1.18.0.tar.gz
正在解析主机 nginx.org (nginx.org)... 52.58.199.22, 3.125.197.172, 2a05:d014:edb:5704::6, ...
正在连接 nginx.org (nginx.org)|52.58.199.22|:80... 已连接。
已发出 HTTP 请求,正在等待回应... 200 OK
长度:1039530 (1015K) [application/octet-stream]
正在保存至: “nginx-1.18.0.tar.gz”

100%[===================================================================================================================================================>] 1,039,530    620KB/s 用时 1.6s   

2023-03-11 01:44:18 (620 KB/s) - 已保存 “nginx-1.18.0.tar.gz” [1039530/1039530])

[root@localhost opt]# ls
nginx-1.18.0.tar.gz  rh
[root@localhost opt]# tar xf nginx-1.18.0.tar.gz   #解压软件包
 
[root@localhost opt]# ls
nginx-1.18.0  nginx-1.18.0.tar.gz  rh
[root@localhost opt]# cd nginx-1.18.0/ 

[root@localhost nginx-1.18.0]# mkdir /apps/nginx -p   

[root@localhost nginx-1.18.0]# ./configure --prefix=/apps/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
##################################################
复制下面代码即可
./configure --prefix=/apps/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
##################################################


[root@localhost nginx-1.18.0]# make && make install
[root@localhost nginx-1.18.0]# chown -R nginx.nginx    #修改权限
 /apps/nginx
[root@localhost nginx-1.18.0]# ll /apps/nginx/
总用量 4
drwxr-xr-x. 2 nginx nginx 4096 311 01:49 conf
drwxr-xr-x. 2 nginx nginx   40 311 01:49 html
drwxr-xr-x. 2 nginx nginx    6 311 01:49 logs
drwxr-xr-x. 2 nginx nginx   19 311 01:49 sbin

######安装好后生成四个文件功能如下######

  1. conf:保存nginx所有的配置文件,其中nginx.conf是nginx服务器的最核心最主要的配置文件,其他的.conf则是用来配置nginx相关的功能的,例如fastcgi功能使用的是fastcgi.conf和fastcgi_params两个文件,配置文件一般都有个样板配置文件,是文件名.default结尾,使用的使用将其复制为并将default去掉即可。
  2. html目录中保存了nginx服务器的web文件,但是可以更改为其他目录保存web文件,另外还有一个50x的web文件是默认的错误页面提示页面。
  3. logs:用来保存nginx服务器的访问日志错误日志等日志,logs目录可以放在其他路径,比如/var/logs/nginx里面。
  4. sbin:保存nginx二进制启动脚本,可以接受不同的参数以实现不同的功能。

创建Nginx 自启动文件

######### 在原有的配置文件基础上插入新增和修改配置信息#########
[root@localhost nginx-1.18.0]# vim /usr/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=/apps/nginx/run/nginx.pid
#注意文件位置,如果不对 启动不了
ExecStart=/apps/nginx/sbin/nginx -c /apps/nginx/conf/nginx.conf
#注意启动文件位置
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s TERM $MAINPID
[Install]
WantedBy=multi-user.target

在这里插入图片描述

[root@localhost nginx-1.18.0]# mkdir /apps/nginx/run/    #创建目录
[root@localhost nginx-1.18.0]# vim /apps/nginx/conf/nginx.conf   #修改配置文件

#找到 pid的位置将以下路径修改
pid   /apps/nginx/run/nginx.pid;

在这里插入图片描述

[root@localhost nginx-1.18.0]# systemctl daemon-reload      #重新加载配置
[root@localhost nginx-1.18.0]# systemctl enable --now nginx
#开机自启并立即启动    如果卡主是应为logs下有 nginx.pid  文件  删除即可
Created symlink from /etc/systemd/system/multi-user.target.wants/nginx.service to /usr/lib/systemd/system/nginx.service.


[root@localhost nginx-1.18.0]# systemctl status nginx   
#####查看nginx状态#####

● nginx.service - The nginx HTTP and reverse proxy server
   Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
   Active: active (running) since 五 2023-03-10 13:38:45 CST; 23h ago
     Docs: http://nginx.org/en/docs/
 Main PID: 39486 (nginx)
   CGroup: /system.slice/nginx.service
           ├─39486 nginx: master process /usr/sbin/nginx
           ├─39487 nginx: worker process
           └─39488 nginx: worker process

310 13:38:45 localhost.localdomain systemd[1]: Starting The nginx HTTP and....
310 13:38:45 localhost.localdomain nginx[39481]: nginx: the configuration f...
310 13:38:45 localhost.localdomain nginx[39481]: nginx: configuration file ...
310 13:38:45 localhost.localdomain systemd[1]: Started The nginx HTTP and ....
Hint: Some lines were ellipsized, use -l to show in full.
[root@localhost nginx-1.18.0]# chown -R nginx.nginx /apps/nginx   #修改权限

在这里插入图片描述
输入ip地址可查看NGINX是否开启成功
在这里插入图片描述

了解配置详细信息

nginx 官方帮助文档:http://nginx.org/en/docs/

tengine 帮助文档:http://tengine.taobao.org/nginx_docs/cn/docs/

Nginx的配置文件的组成部分:

主配置文件:nginx.conf

子配置文件: include conf.d/*.conf

配置文件由指令和指令块构成
每条指令以;分号结尾,指令与值之间以空格符号分隔
指令已{}达括号将多条指令组织在一起且可以嵌套指令块
include语句允许组合多个配置文件以提升可维护性
#号注释
$使用变量
部分支持正则
自定义变量:由用户使用set命令定义,格式: set variable_name value

main block:主配置段,即全局配置段,对http,mail都有效



#事件驱动相关的配置
event {
 ...
}   
#http/https 协议相关配置段
http {
 ...
}          
#默认配置文件不包括下面两个块
#mail 协议相关配置段
mail {
 ...
}    
#stream 服务器相关配置段
stream {负载均衡
 ...
}

#全局配置端,对全局生效,主要设置nginx的启动用户/组,启动的工作进程数量,工作模式,Nginx的PID路径,日志路径等。

user nginx nginx;
worker_processes  1;   #启动工作进程数数量
events { #events设置快,主要影响nginx服务器与用户的网络连接,比如是否允许同时接受多个网络连接,使用哪种事件驱动模型处理请求,每个工作进程可以同时支持的最大连接数,是否开启对多工作进程下的网络连接进行序列化等。

worker_connections  1024;   #设置单个nginx工作进程可以接受的最大并发,作为web服务器的时候最大并发数为worker_connections * worker_processes,作为反向代理的时候为
(worker_connections * worker_processes)/2
}

http { #http块是Nginx服务器配置中的重要部分,缓存、代理和日志格式定义等绝大多数功能和第三方模块都可以在这设置,http块可以包含多个server块,而一个server块中又可以包含多个location块,server块可以配置文件引入、MIME-Type定义、日志自定义、是否启用sendfile、连接超时时间和单个链接的请求上限等。
   include       mime.types;
   default_type application/octet-stream;
   sendfile       on; #作为web服务器的时候打开sendfile加快静态文件传输,指定是否使用sendfile系统调用来传输文件,sendfile系统调用在两个文件描述符之间直接传递数据(完全在内核中操作),从而避免了数据在内核缓冲区和用户缓冲区之间的拷贝,操作效率很高,被称之为零拷贝,硬盘 >> 
kernel buffer (快速拷贝到kernelsocket buffer) >>协议栈。

keepalive_timeout  65;  #长连接超时时间,单位是秒
   server { #设置一个虚拟机主机,可以包含自己的全局快,同时也可以包含多个location模块。比如本虚拟机监听的端口、本虚拟机的名称和IP配置,多个server 可以使用一个端口,比如都使用80端口提供web服务、
       listen       80;  #配置server监听的端口
   server_name localhost; #本server的名称,当访问此名称的时候nginx会调用当前serevr内部的配置进程匹配。3.2 全局配置Main 全局配置段常见的配置指令分类正常运行必备的配优化性能相关的配置用于调试及定位问题相关的配置事件驱动相关的配置


###############################################全局配置说明:################################################################
      location / { 
           root   html;
           index index.html index.htm; 
       }
       error_page   500 502 503 504 /50x.html; 
       location = /50x.html {
           root   html;  
       }
   }
}
################################################################

location / { #location其实是server的一个指令,为nginx服务器提供比较多而且灵活的指令,都是在location中体现的,主要是基于nginx接受到的请求字符串,对用户请求的UIL进行匹配,并对特定的指令进行处理,包括地址重定向、数据缓存和应答控制等功能都是在这部分实现,另外很多第三方模块的配置也是在location模块中配置。
           root   html; #相当于默认页面的目录名称,默认是安装目录的相对路径,可以使用绝对路径配置。
           index index.html index.htm; #默认的页面文件名称
       }     
       error_page   500 502 503 504 /50x.html; #错误页面的文件名称
       location = /50x.html { #location处理对应的不同错误码的页面定义到/50x.html,这个跟对应其server中定义的目录下。
           root   html;  #定义默认页面所在的目录
       }
   }

#和邮件相关的配置
#mail {
#               ...
#       }         mail 协议相关配置段
#tcp代理配置,1.9版本以上支持
#stream {
#               ...
#       }       stream 服务器相关配置段
#导入其他路径的配置文件
#include /apps/nginx/conf.d/*.conf
}

全局配置

nginx 有多种模块

  • 核心模块:是 Nginx 服务器正常运行必不可少的模块,提供错误日志记录 、配置文件解析 、事件驱动机制 、进程管理等核心功能
  • 标准HTTP模块:提供 HTTP 协议解析相关的功能,比如: 端口配置 、 网页编码设置 、 HTTP响应头设置 等等
  • 可选HTTP模块:主要用于扩展标准的 HTTP 功能,让 Nginx 能处理一些特殊的服务,比如:Flash 多媒体传输 、解析 GeoIP 请求、 网络传输压缩 、 安全协议 SSL 支持等
  • 邮件服务模块:主要用于支持 Nginx 的 邮件服务 ,包括对 POP3 协议、 IMAP 协议和 SMTP协议的支持
  • Stream服务模块: 实现反向代理功能,包括TCP协议代理
  • 第三方模块:是为了扩展 Nginx 服务器应用,完成开发者自定义功能,比如: Json 支持、 Lua 支持等

平滑升级

在这里插入图片描述

  1. 向master进程发送USR2信号
  2. master进程修改pid文件名,加后缀.oldbin
  3. master进程用新Nginx文件启动新master进程,系统中将有新旧两个Nginx主进程共同提供Web服务
  4. 向旧的Nginx服务进程发送WINCH信号,使旧的Nginx worker进程平滑停止,并删除Nginx.pid.oldbin文件
  5. 向旧master进程发送QUIT信号,关闭老master
  6. 如果发现升级有问题,可以回滚向老master发送HUP,向新master发送QUIT

升级

[root@localhost ~]# ps aux |grep nginx
#先查看是否开启nginx

root      39486  0.0  0.0  41412  1004 ?        Ss   22:53   0:00 nginx: master process /usr/sbin/nginx
nginx     39487  0.0  0.0  43884  1496 ?        S    22:53   0:00 nginx: worker process
nginx     39488  0.0  0.0  43884  1700 ?        S    22:53   0:00 nginx: worker process
root      45509  0.0  0.0 112824   980 pts/0    S+   23:53   0:00 grep --color=auto nginx

[root@localhost ~]#vim /apps/nginx/conf/nginx.conf
#开启 两核
#user  nobody;
worker_processes  2;

#worker_processes  1 原来是1

在这里插入图片描述

[root@localhost nginx-1.18.0]# lscpu   ##检查cpu核数,以防万一
Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                2
On-line CPU(s) list:   0,1
Thread(s) per core:    1
Core(s) per socket:    1
座:                 2
NUMA 节点:         1
厂商 ID:           AuthenticAMD
CPU 系列:          23
型号:              96
型号名称:        AMD Ryzen 5 4600H with Radeon Graphics
步进:              1
CPU MHz2993.671
BogoMIPS5988.75
超管理器厂商:  VMware
虚拟化类型:     完全
L1d 缓存:          32K
L1i 缓存:          32K
L2 缓存:           512K
L3 缓存:           4096K
NUMA 节点0 CPU:    0,1
Flags:                 fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc art rep_good nopl tsc_reliable nonstop_tsc extd_apicid eagerfpu pni pclmulqdq ssse3 fma cx16 sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw topoext fsgsbase bmi1 avx2 smep bmi2 rdseed adx smap clflushopt clwb sha_ni xsaveopt xsavec xgetbv1 arat overflow_recov succor

在这里插入图片描述

[root@localhost nginx-1.18.0]# ps aux |grep nginx
root      39486  0.0  0.0  41468  2012 ?        Ss   22:53   0:00 nginx: master process /usr/sbin/nginx
nginx     47350  0.0  0.0  44024  2012 ?        S    23:59   0:00 nginx: worker process
nginx     47351  0.0  0.0  44024  2000 ?        S    23:59   0:00 nginx: worker process
root      47359  0.0  0.0 112824   980 pts/0    S+   23:59   0:00 grep --color=auto nginx
[root@localhost nginx-1.18.0]# ps auxf |grep nginx
root      47382  0.0  0.0 112824   980 pts/0    S+   23:59   0:00      \_ grep --color=auto nginx
root      39486  0.0  0.0  41468  2012 ?        Ss   22:53   0:00 nginx: master process /usr/sbin/nginx
nginx     47350  0.0  0.0  44024  2012 ?        S    23:59   0:00  \_ nginx: worker process
nginx     47351  0.0  0.0  44024  2000 ?        S    23:59   0:00  \_ nginx: worker process


[root@localhost nginx-1.18.0]# wget https://nginx.org/download/nginx-1.22.1.tar.gz -P /usr/local/src/
#下载安装包到src目录
--2023-03-13 00:00:24--  https://nginx.org/download/nginx-1.22.1.tar.gz
正在解析主机 nginx.org (nginx.org)... 3.125.197.172, 52.58.199.22, 2a05:d014:edb:5702::6, ...
正在连接 nginx.org (nginx.org)|3.125.197.172|:443... 已连接。
已发出 HTTP 请求,正在等待回应... 200 OK
长度:1073948 (1.0M) [application/octet-stream]
正在保存至:/usr/local/src/nginx-1.22.1.tar.gz”

100%[====================================>] 1,073,948    881KB/s 用时 1.2s   

2023-03-13 00:00:26 (881 KB/s) - 已保存 “/usr/local/src/nginx-1.22.1.tar.gz” [1073948/1073948])

[root@localhost nginx-1.18.0]# cd /usr/local/src/
[root@localhost src]# ls
nginx-1.22.1.tar.gz
[root@localhost src]# tar xf nginx-1.22.1.tar.gz
[root@localhost src]# cd nginx-1.22.1/
[root@localhost nginx-1.22.1]# ls
auto     CHANGES.ru  configure  html     man     src
CHANGES  conf        contrib    LICENSE  README

[root@localhost nginx-1.22.1]# ./configure --prefix=/apps/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

[root@localhost nginx-1.22.1]# make
###########注意不要执行  make install

[root@localhost nginx-1.22.1]# cd objs
#此文件夹中有新版本的nginx  运行程序

[root@localhost objs]# ls
autoconf.err  nginx    ngx_auto_config.h   ngx_modules.c  src
Makefile      nginx.8  ngx_auto_headers.h  ngx_modules.o


[root@localhost objs]# mv /apps/nginx/sbin/nginx   /apps/nginx/sbin/nginx.bak
#将低版本的nginx主程序改名
[root@localhost objs]# #cp /usr/local/src/nginx-1.20.2/objs/nginx /apps/nginx/sbin/
#将新版本 拷入进去

[root@localhost objs]# ll /apps/nginx/sbin/
总用量 15308
-rwxr-xr-x. 1 root  root  7896080 323 11:54 nginx
-rwxr-xr-x. 1 nginx nginx 7774624 323 11:47 nginx.bak

[root@localhost objs]# /apps/nginx/sbin/nginx -t
#检查下语法问题
nginx: the configuration file /apps/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /apps/nginx/conf/nginx.conf test is successful

[root@localhost objs]# ps aux |grep nginx
root       7579  0.0  0.0  46204  1164 ?        Ss   11:49   0:00 nginx: master process /apps/nginx/sbin/nginx -c /apps/nginx/conf/nginx.conf
nginx      7580  0.0  0.0  48736  1996 ?        S    11:49   0:00 nginx: worker process
root      10766  0.0  0.0 112824   980 pts/0    R+   11:57   0:00 grep --color=auto nginx

[root@localhost objs]# kill -USR2 7579

[root@localhost objs]# ps aux |grep nginx
root       7579  0.0  0.0  46204  1356 ?        Ss   11:49   0:00 nginx: master process /apps/nginx/sbin/nginx -c /apps/nginx/conf/nginx.conf
nginx      7580  0.0  0.0  48736  1996 ?        S    11:49   0:00 nginx: worker process
root      10789  0.0  0.1  46220  3368 ?        S    11:57   0:00 nginx: master process /apps/nginx/sbin/nginx -c /apps/nginx/conf/nginx.conf
nginx     10793  0.0  0.0  48756  1996 ?        S    11:57   0:00 nginx: worker process
root      10807  0.0  0.0 112824   980 pts/0    R+   11:58   0:00 grep --color=auto nginx

[root@localhost objs]# ps auxf|grep nginx
#生成新的master
root      10828  0.0  0.0 112824   980 pts/0    S+   11:58   0:00      \_ grep --color=auto nginx
root       7579  0.0  0.0  46204  1356 ?        Ss   11:49   0:00 nginx: master process /apps/nginx/sbin/nginx -c /apps/nginx/conf/nginx.conf
nginx      7580  0.0  0.0  48736  1996 ?        S    11:49   0:00  \_ nginx: worker process
root      10789  0.0  0.1  46220  3368 ?        S    11:57   0:00  \_ nginx: master process /apps/nginx/sbin/nginx -c /apps/nginx/conf/nginx.conf
nginx     10793  0.0  0.0  48756  1996 ?        S    11:57   0:00      \_ nginx: worker process

[root@localhost objs]# lsof -i :80
#查看谁在监听 80
COMMAND   PID  USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
nginx    7579  root    6u  IPv4  40654      0t0  TCP *:http (LISTEN)
nginx    7580 nginx    6u  IPv4  40654      0t0  TCP *:http (LISTEN)
nginx   10789  root    6u  IPv4  40654      0t0  TCP *:http (LISTEN)
nginx   10793 nginx    6u  IPv4  40654      0t0  TCP *:http (LISTEN)

[root@localhost objs]# cd /apps/nginx/html/
[root@localhost html]# dd if=/dev/zero of=/apps/nginx/html/m.img bs=1G count=10
记录了10+0 的读入
记录了10+0 的写出
10737418240字节(11 GB)已复制,35.2953 秒,304 MB/[root@localhost html]# ls
50x.html  index.html  m.img


[root@localhost html]# systemctl stop firewalld.service && setenforce 0
### 关闭防护墙

开启一台新的虚拟机下载m.img

[root@localhost ~]# systemctl stop firewalld.service && setenforce 0
###关闭防火墙
[root@localhost ~]# ping 20.0.0.100
### ping一下主虚拟机查看能否连通
PING 20.0.0.100 (20.0.0.100) 56(84) bytes of data.
64 bytes from 20.0.0.100: icmp_seq=1 ttl=64 time=0.720 ms
64 bytes from 20.0.0.100: icmp_seq=2 ttl=64 time=0.407 ms
64 bytes from 20.0.0.100: icmp_seq=3 ttl=64 time=0.334 ms
^C
--- 20.0.0.100 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2001ms
rtt min/avg/max/mdev = 0.334/0.487/0.720/0.167 ms


[root@localhost ~]# curl 20.0.0.100
### 请求 Web 服务器查看是否能请求成功
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

[root@localhost ~]# cd /
[root@localhost /]# ls
bin   dev  home  lib64  mnt  proc  run   srv  tmp  var
boot  etc  lib   media  opt  root  sbin  sys  usr
[root@localhost /]# mkdir data
[root@localhost /]# cd data

[root@localhost data]# wget --limit-rate=1M http://20.0.0.100/m.img
--2023-03-23 12:10:13--  http://20.0.0.100/m.img
正在连接 20.0.0.100:80... 已连接。
已发出 HTTP 请求,正在等待回应... 200 OK
长度:10737418240 (10G) [application/octet-stream]
正在保存至: “m.img”

100%[=====================================>] 10,737,418,240 1.01MB/s 用时 2h 51m 

2023-03-23 15:01:19 (1021 KB/s) - 已保存 “m.img” [10737418240/10737418240])

切回20.0.0.100虚拟机网页服务器

[root@localhost html]# ss -ntap|grep 80
#查看那个进程在管理 下载(20.0.0.200:56500正在下载)
LISTEN     0      128          *:80                       *:*                   users:(("nginx",pid=10793,fd=6),("nginx",pid=10789,fd=6),("nginx",pid=7579,fd=6))
ESTAB      0      516288 20.0.0.100:80                 20.0.0.200:56500               users:(("nginx",pid=10793,fd=3))

[root@localhost html]# ls /apps/nginx/run/
#会有 新老两个进程
nginx.pid(新进程)  nginx.pid.oldbin(老进程)
[root@localhost html]# cat /apps/nginx/run/nginx.pid.oldbin
7579
[root@localhost html]# ps aux |grep nginx
root       7579  0.0  0.0  46204  1260 ?        Ss   11:51   0:00 nginx: master process /apps/nginx/sbin/nginx -c /apps/nginx/conf/nginx.conf
nginx      7580  0.0  0.0  48736  1844 ?        S    11:51   0:00 nginx: worker process
root      10789  0.0  0.1  46220  2960 ?        S    12:00   0:00 nginx: master process /apps/nginx/sbin/nginx -c /apps/nginx/conf/nginx.conf
nginx     10793  0.1  0.1  48756  2096 ?        S    12:00   0:17 nginx: worker process
root      51853  0.0  0.0 112824   980 pts/0    R+   15:36   0:00 grep --color=auto nginx


[root@localhost html]# kill -WINCH 7579
#优雅关闭老进程的  worker 进程
[root@localhost html]# ps aux |grep nginx
root       7579  0.0  0.0  46204  1260 ?        Ss   11:51   0:00 nginx: master process /apps/nginx/sbin/nginx -c /apps/nginx/conf/nginx.conf
root      10789  0.0  0.1  46220  2960 ?        S    12:00   0:00 nginx: master process /apps/nginx/sbin/nginx -c /apps/nginx/conf/nginx.conf
nginx     10793  0.1  0.1  48756  2096 ?        S    12:00   0:18 nginx: worker process
root      52103  0.0  0.0 112824   980 pts/0    S+   15:59   0:00 grep --color=auto nginx

再开启一台虚拟机服务器测试 是否是新的进程 在下载

[root@localhost ~]# cd /
[root@localhost /]# ks
bash: ks: 未找到命令...
[root@localhost /]# ls
bin   dev  home  lib64  mnt  proc  run   srv  tmp  var
boot  etc  lib   media  opt  root  sbin  sys  usr
[root@localhost /]# mkdir data
[root@localhost /]# systemctl stop firewalld.service && setenforce 0
[root@localhost /]# wget --limit-rate=1M http://20.0.0.100/m.img
--2023-03-24 16:00:44--  http://20.0.0.100/m.img
正在连接 20.0.0.100:80... 已连接。
已发出 HTTP 请求,正在等待回应... 200 OK
长度:10737418240 (10G) [application/octet-stream]
正在保存至: “m.img”

 1% [=>                                                                                                                                                  ] 177,315,840 1024KB/s 剩余 2h 47m                                                                                                     

回到网页服务器可以看到 之前的在 担忧开启了一个 210

[root@localhost html]# ss -ntap|grep 80
LISTEN     0      128          *:80                       *:*                   users:(("nginx",pid=10793,fd=6),("nginx",pid=10789,fd=6),("nginx",pid=7579,fd=6))
ESTAB      0      465808 20.0.0.100:80                 20.0.0.210:36136               users:(("nginx",pid=10793,fd=3))
[root@localhost html]# pstree -p |grep nginx
           |-nginx(7579)---nginx(10789)---nginx(10793)

回滚-唤醒老进程

[root@localhost html]# kill -HUP 7579
#唤起老的进程
[root@localhost html]# ps aux |grep nginx
root       7579  0.0  0.0  46204  1332 ?        Ss   13:05   0:00 nginx: master process /apps/nginx/sbin/nginx -c /apps/nginx/conf/nginx.conf
root      10789  0.0  0.1  46220  3332 ?        S    13:14   0:00 nginx: master process /apps/nginx/sbin/nginx -c /apps/nginx/conf/nginx.conf
nginx     10793  0.1  0.1  48756  2188 ?        S    13:14   0:16 nginx: worker process
nginx     50084  0.0  0.0  48736  1976 ?        S    16:33   0:00 nginx: worker process
root      50091  0.0  0.0 112824   980 pts/0    S+   16:33   0:00 grep --color=auto nginx



[root@localhost data]# curl -I 20.0.0.100 
## 在另外一台虚拟机查看网页服务器 1.20.2 表示新版本正在下载中
HTTP/1.1 200 OK
Server: nginx/1.20.2
Date: Fri, 24 Mar 2023 08:44:41 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Thu, 23 Mar 2023 03:47:52 GMT
Connection: keep-alive
ETag: "641bcbe8-264"
Accept-Ranges: bytes


kill -QUIT 【进程号】   如果升级有问题,杀新的进程
[root@localhost html]# ps aux |grep nginx
root       7579  0.0  0.0  46204  1280 ?        Ss   13:22   0:00 nginx: master process /apps/nginx/sbin/nginx -c /apps/nginx/conf/nginx.conf
nginx      7580  0.0  0.1  48736  2112 ?        S    13:22   0:00 nginx: worker process
root      10789  0.0  0.1  46220  2972 ?        S    13:31   0:00 nginx: master process /apps/nginx/sbin/nginx -c /apps/nginx/conf/nginx.conf
nginx     10793  0.1  0.1  48756  2112 ?        S    13:31   0:16 nginx: worker process
root      51948  0.0  0.0 112824   976 pts/0    S+   16:50   0:00 grep --color=auto nginx
[root@localhost html]# kill -QUIT 7580
## 杀掉进程
[root@localhost html]# ps aux |grep nginx
root       7579  0.0  0.0  46204  1280 ?        Ss   13:22   0:00 nginx: master process /apps/nginx/sbin/nginx -c /apps/nginx/conf/nginx.conf
root      10789  0.0  0.1  46220  2972 ?        S    13:31   0:00 nginx: master process /apps/nginx/sbin/nginx -c /apps/nginx/conf/nginx.conf
nginx     10793  0.1  0.1  48756  2112 ?        S    13:31   0:16 nginx: worker process
nginx     52012  0.0  0.0  48736  1976 ?        S    16:50   0:00 nginx: worker process
root      52017  0.0  0.0 112824   980 pts/0    R+   16:50   0:00 grep --color=auto nginx



## 在另外一台虚拟机查看网页服务器 1.20.2 表示版本回滚到了1.18.0[root@localhost data]# curl -I 20.0.0.100
HTTP/1.1 200 OK
Server: nginx/1.18.0
Date: Fri, 24 Mar 2023 08:50:56 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Thu, 23 Mar 2023 03:47:52 GMT
Connection: keep-alive
ETag: "641bcbe8-264"
Accept-Ranges: bytes

在这里插入图片描述

配置详细解释

nginx 官方帮助文档:http://nginx.org/en/docs/
在这里插入图片描述
在这里插入图片描述
tengine 帮助文档:http://tengine.taobao.org/nginx_docs/cn/docs/

Nginx的配置文件的组成部分:
主配置文件:nginx.conf
子配置文件: include conf.d/*.conf

配置文件由指令和指令块构成
每条指令以;分号结尾,指令与值之间以空格符号分隔
pid    /apps/run/nginx.pid
指令已{}达括号将多条指令组织在一起且可以嵌套指令块
include语句允许组合多个配置文件以提升可维护性 
#号注释
$使用变量
部分支持正则
自定义变量:由用户使用set命令定义,格式: set variable_name value

main block:主配置段,即全局配置段,对http,mail都有效

#事件驱动相关的配置   同步
event {
 ...
}   
#http/https 协议相关配置段
http {
 ...
}          
#默认配置文件不包括下面两个块
#mail 协议相关配置段
mail {
 ...
}    
#stream 服务器相关配置段
stream {负载均衡
 ...
}

全局配置

nginx 有多种模块

  • 核心模块:是 Nginx 服务器正常运行必不可少的模块,提供错误日志记录 、配置文件解析 、事件驱动机制 、进程管理等核心功能
  • 标准HTTP模块:提供 HTTP 协议解析相关的功能,比如: 端口配置 、 网页编码设置 、 HTTP响应头设置 等等
  • 可选HTTP模块:主要用于扩展标准的 HTTP 功能,让 Nginx 能处理一些特殊的服务,比如:Flash 多媒体传输 、解析 GeoIP 请求、 网络传输压缩 、 安全协议 SSL 支持等
  • 邮件服务模块:主要用于支持 Nginx 的 邮件服务 ,包括对 POP3 协议、 IMAP 协议和 SMTP协议的支持
  • Stream服务模块: 实现反向代理功能,包括TCP协议代理
  • 第三方模块:是为了扩展 Nginx 服务器应用,完成开发者自定义功能,比如: Json 支持、 Lua 支持等

关闭版本

[root@localhost ~]# vim /apps/nginx/conf/nginx.conf

http {
    include       mime.types;
    default_type  application/octet-stream;
    server_tokens  off;


[root@localhost nginx]#nginx -s reload
#重新加载

验证
[root@localhost sbin]#curl -I 20.0.0.100
HTTP/1.1 200 OK
Server: nginx/1.18.0
Date: Fri, 24 Mar 2023 12:22:47 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Thu, 23 Mar 2023 03:47:52 GMT
Connection: keep-alive
ETag: "641bcbe8-264"
Accept-Ranges: bytes


[root@localhost sbin]#curl -I 20.0.0100
HTTP/1.1 200 OK
Server: nginx
Date: Fri, 24 Mar 2023 12:22:47 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Thu, 23 Mar 2023 03:47:52 GMT
Connection: keep-alive
ETag: "641bcbe8-264"
Accept-Ranges: bytes


在这里插入图片描述

修改版本

[root@localhost html]# systemctl stop nginx
## 修改前需先停nginx服务

[root@localhost ~]# cd /opt/nginx-1.18.0/src/core/
[root@localhost core]#vim  /opt/nginx-1.18.0/src/core/nginx.h

 13 #define NGINX_VERSION      "9527"
 14 #define NGINX_VER          "zhangsan/" NGINX_VERSION

在这里插入图片描述

[root@localhost core]# vim /opt/nginx-1.18.0/src/http/ngx_http_header_filter_module.c 

 49 static u_char ngx_http_server_string[] = "Server: zhangsan" CRLF;

在这里插入图片描述

[root@localhost core]# cd ../../
[root@localhost nginx-1.18.0]# ./configure --prefix=/apps/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

===================================================
./configure --prefix=/apps/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
===================================================

[root@localhost nginx-1.18.0]# make && make install


[root@localhost nginx-1.18.0]# systemctl start nginx
[root@localhost nginx-1.18.0]# systemctl status nginx
###查看nginx是否正常开启
● nginx.service - nginx - high performance web server
   Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
   Active: active (running) since 五 2023-03-24 20:46:29 CST; 10s ago
     Docs: http://nginx.org/en/docs/
  Process: 49997 ExecStop=/bin/kill -s TERM $MAINPID (code=exited, status=0/SUCCESS)
  Process: 51397 ExecStart=/apps/nginx/sbin/nginx -c /apps/nginx/conf/nginx.conf (code=exited, status=0/SUCCESS)
 Main PID: 51398 (nginx)
   CGroup: /system.slice/nginx.service
           ├─51398 nginx: master process /apps/nginx/sbin/nginx -c /apps/nginx/...
           └─51399 nginx: worker process

324 20:46:29 localhost.localdomain systemd[1]: Starting nginx - high perfo....
324 20:46:29 localhost.localdomain systemd[1]: Started nginx - high perfor....
Hint: Some lines were ellipsized, use -l to show in full.


[root@localhost nginx-1.18.0]# curl -I 20.0.0.100 
### 查看自身版本是否修改成功
HTTP/1.1 200 OK
Server: zhangsan/9527
Date: Fri, 24 Mar 2023 12:49:19 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Thu, 23 Mar 2023 03:47:52 GMT
Connection: keep-alive
ETag: "641bcbe8-264"
Accept-Ranges: bytes

修改启动的进程数

[root@localhost ~]# vim /apps/nginx/conf/nginx.conf


#user  nobody;
worker_processes  1;
#允许的启动工作进程数数量,和你真实的cpu数量有关   1

worker_processes auto;
#如果设置为auto  就是你真实的cpu数量

[root@localhost ~]# nginx -s reload

[root@localhost ~]# ps axo pid,cmd,psr,ni|grep nginx
#可以看到 nginx的  worker数量
 54963 nginx: master process /apps   1   0
 54964 nginx: worker process         1   0
 55085 grep --color=auto nginx       1   0

[root@localhost ~]# lscpu  
## 可查看
Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                1
On-line CPU(s) list:   0,1
Thread(s) per core:    1
Core(s) per socket:    1
座:                 2
NUMA 节点:         1
厂商 ID:           AuthenticAMD
CPU 系列:          23
型号:              96
型号名称:        AMD Ryzen 5 4600H with Radeon Graphics
步进:              1
CPU MHz2993.671
BogoMIPS5988.75
超管理器厂商:  VMware
虚拟化类型:     完全
L1d 缓存:          32K
L1i 缓存:          32K
L2 缓存:           512K
L3 缓存:           4096K
NUMA 节点0 CPU:    0,1
Flags:                 fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc art rep_good nopl tsc_reliable nonstop_tsc extd_apicid eagerfpu pni pclmulqdq ssse3 fma cx16 sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw topoext fsgsbase bmi1 avx2 smep bmi2 rdseed adx smap clflushopt clwb sha_ni xsaveopt xsavec xgetbv1 arat overflow_recov succor

在这里插入图片描述

cpu与work进程绑定(亲缘性)

将Nginx工作进程绑定到指定的CPU核心,默认Nginx是不进行进程绑定的,绑定并不是意味着当前nginx进程独占以一核心CPU,但是可以保证此进程不会运行在其他核心上,这就极大减少了nginx的工作进程在不同的cpu核心上的来回跳转,减少了CPU对进程的资源分配与回收以及内存管理等,因此可以有效的提升nginx服务器的性能。

CPU序号:
CPU MASK: 000000010号CPU
          000000101号CPU
          ................
  		  100000007号CPU
worker_cpu_affinity 00000001 00000010 00000100 00001000;0---3号CPU   
#序号绑定cpu    亲缘性
worker_cpu_affinity 00000101 00001010;
#同一个work  可以绑定  两个cpu可以这么写 但是不建议,本来就是 不希望飘动,这样也是飘动


[root@localhost ~]# vim /apps/nginx/conf/nginx.conf

#user  nobody;
worker_processes  auto;

[root@localhost ~]# nginx -s reload

在这里插入图片描述

[root@localhost ~]# ps axo pid,cmd,psr,ni|grep nginx|sort -n
 39486 nginx: master process /usr/   0   0
 49424 nginx: worker process         1   0
 49425 nginx: worker process         0   0
 49427 grep --color=auto nginx       1   0
[root@localhost ~]# ps axo pid,cmd,psr,ni|grep nginx|sort -n
 39486 nginx: master process /usr/   0   0
 49424 nginx: worker process         0   0
 49425 nginx: worker process         1   0
 49442 grep --color=auto nginx       1   0
[root@localhost ~]# ps axo pid,cmd,psr,ni|grep nginx|sort -n
 39486 nginx: master process /usr/   0   0
 49424 nginx: worker process         0   0
 49425 nginx: worker process         1   0
 49451 grep --color=auto nginx       1   0
[root@localhost ~]# ps axo pid,cmd,psr,ni|grep nginx|sort -n
 39486 nginx: master process /usr/   0   0
 49424 nginx: worker process         0   0
 49425 nginx: worker process         1   0
 49460 grep --color=auto nginx       1   0


验证cpu乱跑可以刷新网页即可

在这里插入图片描述

新增 worker_cpu_affinity 00000101 00001010; 可防止CPU乱跑

[root@localhost ~]# vim /apps/nginx/conf/nginx.conf

#user  nobody;
worker_processes  auto;
worker_cpu_affinity 00000101 00001010;


[root@localhost ~]# nginx -s reload

在这里插入图片描述

[root@localhost ~]# ps axo pid,cmd,psr,ni|grep nginx|sort -n
 39486 nginx: master process /usr/   1   0
 45569 nginx: worker process         0   0
 45570 nginx: worker process         1   0
 45572 grep --color=auto nginx       0   0
[root@localhost ~]# ps axo pid,cmd,psr,ni|grep nginx|sort -n
 39486 nginx: master process /usr/   1   0
 45569 nginx: worker process         0   0
 45570 nginx: worker process         1   0
 45581 grep --color=auto nginx       0   0
[root@localhost ~]# ps axo pid,cmd,psr,ni|grep nginx|sort -n
 39486 nginx: master process /usr/   1   0
 45569 nginx: worker process         0   0
 45570 nginx: worker process         1   0
 45590 grep --color=auto nginx       0   0
[root@localhost ~]# ps axo pid,cmd,psr,ni|grep nginx|sort -n
 39486 nginx: master process /usr/   1   0
 45569 nginx: worker process         0   0
 45570 nginx: worker process         1   0
 45599 grep --color=auto nginx       0   0
[root@localhost ~]# ps axo pid,cmd,psr,ni|grep nginx|sort -n
 39486 nginx: master process /usr/   1   0
 45569 nginx: worker process         0   0
 45570 nginx: worker process         1   0
 45608 grep --color=auto nginx       0   0

在这里插入图片描述

PID 路径

[root@localhost ~]# vim /apps/nginx/conf/nginx.conf

pid        /apps/nginx/run/nginx.pid;

pid  进程号文件位置可以自定义省略

在这里插入图片描述

nginx进程的优先级(work进程的优先级)

当你想将nginx的work进程的优先级调高 可以使用nice设置

nice的优先级是  -2019

worker_priority 0; 
#工作进程优先级,-20~20(19)


在这里插入图片描述

[root@localhost ~]# ps axo pid,cmd,psr,ni|grep nginx|sort -n
#查看默认优先级,默认优先级为0
  7579 nginx: master process /apps   0   0
  7580 nginx: worker process         1   0
 10789 nginx: master process /apps   0   0
 10793 nginx: worker process         0   0
 50219 grep --color=auto nginx       1   0

[root@localhost ~]# vim /apps/nginx/conf/nginx.conf

#user  nobody;
worker_processes  auto;
worker_cpu_affinity 00000101 00001010;
worker_priority -20;


[root@localhost ~]# nginx -s reload 
## 重新加载配置文件信息

在这里插入图片描述

[root@localhost ~]# systemctl restart nginx
##需重启nginx
[root@localhost ~]# ps axo pid,cmd,psr,ni|grep nginx|sort -n
 50160 nginx: master process /apps   0   0
 50161 nginx: worker process         0 -20
 50162 nginx: worker process         1 -20
 50170 grep --color=auto nginx       1   0

调试work进程打开的文件的个数

worker_rlimit_nofile 65536;
所有worker进程能打开的文件数量上限,包括:Nginx的所有连接(例如与代理服务器的连接等),而不仅仅是与客户端的连接,另一个考虑因素是实际的并发连接数不能超过系统级别的最大打开文件数的限制.最好与ulimit -n 或者limits.conf的值保持一致,
在这里插入图片描述

[root@localhost ~]# ulimit -a
#单个进程能打开的文件是1024
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 7812
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 1024
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 7812
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

在这里插入图片描述

修改配置文件,最后一段加以下数据,不能有#

[root@localhost ~]#vim /etc/security/limits.conf 


*                soft    core            unlimited
*                hard    core            unlimited
*                soft    nproc           1000000
*                hard    nproc           1000000
*                soft    nofile          1000000
*                hard    nofile          1000000
*                soft    memlock         32000
*                hard    memlock         32000
*                soft    msgqueue        8192000
*                hard    msgqueue        8192000

在这里插入图片描述

[root@localhost ~]# reboot
##配置完之后必须重启服务器

[root@localhost ~]# ulimit -a
##已配置成功
core file size          (blocks, -c) unlimited
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 7812
max locked memory       (kbytes, -l) 32000
max memory size         (kbytes, -m) unlimited
open files                      (-n) 1000000
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 8192000
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 1000000
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited


在这里插入图片描述

不建议用 ulimit -n 65536 ,因为只修改当前窗口

[root@localhost ~]# ulimit -n 65536
[root@localhost ~]# ulimit -a
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 7812
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 65536
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 7812
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

在这里插入图片描述

可以看到打开的连接数

[root@localhost ~]# ps aux |grep nginx
###选择其中一个进程   到proc 下去查看 连接状态
root       1131  0.0  0.0  46204  1164 ?        Ss   22:06   0:00 nginx: master process /apps/nginx/sbin/nginx -c /apps/nginx/conf/nginx.conf
nginx      1135  0.0  0.0  48736  2012 ?        S<   22:06   0:00 nginx: worker process
nginx      1136  0.0  0.0  48736  2012 ?        S<   22:06   0:00 nginx: worker process
root       2536  0.0  0.0 112828   980 pts/0    R+   22:13   0:00 grep --color=auto nginx
[root@localhost ~]# ls /proc/1135/fd
0  1  2  3  4  5  6  7  8  9

在这里插入图片描述

服务是否已后台方式运行

一般服务都是后台运行,前台容器中会用到

[root@localhost ~]# vim /apps/nginx/conf/nginx.conf


#user  nobody;
worker_processes  auto;
worker_cpu_affinity 00000101 00001010;
worker_priority -20;
daemon off;

在这里插入图片描述

重启nginx服务,当前以前台方式运行,使用ctrl+c键可退出

[root@localhost ~]# systemctl restart nginx





^C
[root@localhost ~]# systemctl status nginx
● nginx.service - The nginx HTTP and reverse proxy server
   Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
   Active: activating (start) since 五 2023-03-24 22:39:22 CST; 1min 25s ago
     Docs: http://nginx.org/en/docs/
  Process: 47168 ExecStop=/bin/kill -s TERM $MAINPID (code=exited, status=0/SUCCESS)
  Process: 47175 ExecStartPre=/usr/sbin/nginx -t (code=exited, status=0/SUCCESS)
  Process: 47173 ExecStartPre=/usr/bin/rm -f /run/nginx.pid (code=exited, status=0/SUCCESS)
 Main PID: 39486 (code=exited, status=0/SUCCESS);         : 47178 (nginx)
   CGroup: /system.slice/nginx.service
           ├─47178 nginx: master process /apps/nginx/sbin/nginx -c /apps/nginx/...
           ├─47181 nginx: worker process
           └─47182 nginx: worker process

324 22:39:22 localhost.localdomain systemd[1]: Starting The nginx HTTP and....
324 22:39:22 localhost.localdomain nginx[47175]: nginx: the configuration f...
324 22:39:22 localhost.localdomain nginx[47175]: nginx: configuration file ...
Hint: Some lines were ellipsized, use -l to show in full.

在这里插入图片描述

只有 master进程没有 work进程

实际生产中使用较少

[root@localhost ~]# vim /apps/nginx/conf/nginx.conf


#user  nobody;
worker_processes  auto;
worker_cpu_affinity 00000101 00001010;
worker_priority -20;
master_process off|on;

#是否开启Nginx的master-worker工作模式,仅用于开发调试场景,默认为on

[root@localhost ~]# nginx -s reload

在这里插入图片描述

event事件

[root@localhost ~]# ps axo pid,cmd,psr,ni|grep nginx|sort -n
 39486 nginx: master process /usr/   0   0
 45680 nginx: worker process         0   0
 45681 nginx: worker process         1   0
 45735 grep --color=auto nginx       1   0


[root@localhost ~]# vim /apps/nginx/conf/nginx.conf

events {
   worker_connections  65536;  #设置单个工作进程的最大并发连接数
   use epoll;
   #使用epoll事件驱动,Nginx支持众多的事件驱动,比如:select、poll、epoll,只能设置在events模块中设置。
   accept_mutex on; 
   #on为同一时刻一个请求轮流由work进程处理,而防止被同时唤醒所有worker,避免多个睡眠进程被唤醒的设置,默认为off,新请求会唤醒所有worker进程,此过程也称为"惊群",因此nginx刚安装完以后要进行适当的优化。建议设置为on
   multi_accept on; 
   #ON时Nginx服务器的每个工作进程可以同时接受多个新的网络连接,此指令默认为off,即默认为一个工作进程只能一次接受一个新的网络连接,打开后几个同时接受多个。建议设置为on
}

[root@localhost ~]# nginx -s reload

[root@localhost ~]# systemctl restart nginx
[root@localhost ~]# ps axo pid,cmd,psr,ni|grep nginx|sort -n
 45779 nginx: master process /apps   0   0
 45780 nginx: worker process         0 -20
 45781 nginx: worker process         1 -20
 45789 grep --color=auto nginx       1   0

在这里插入图片描述

http设置

http 是一个大的语句块,包含若干个小的语句块(比如server语句块)

http {
 ...
 ...  #各server的公共配置
 server {    #每个server用于定义一个虚拟主机,第一个server为默认虚拟服务器
 ...
 }
 server {     
 ...
 server_name   #虚拟主机名
 root     #主目录
 alias     #路径别名
 location [OPERATOR] URL {     #指定URL的特性
 ...
 if CONDITION {
 ...
 }
 }
 }
}

http 协议配置说明

[root@localhost ~]# vim /apps/nginx/conf/nginx.conf




http {
   include       mime.types; #导入支持的文件类型,是相对于/apps/nginx/conf的目录
   default_type application/octet-stream; #除mime.types中文件类型外,设置其它文件默认类型,访问其它类型时会提示下载不匹配的类型文件
#日志配置部分
    #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; 
    #tcp_nopush     on; #在开启了sendfile的情况下,合并请求后统一发送给客户端。
    #tcp_nodelay   off; #在开启了keepalived模式下的连接是否启用TCP_NODELAY选项,当为
off时,延迟0.2s发送,默认On时,不延迟发送,立即发送用户响应报文。
    #keepalive_timeout 0;
   keepalive_timeout  65 65; #设置会话保持时间,第二个值为响应首部:keepAlived:timeout=65,可以和第一个值不同
    #gzip on; #开启文件压缩
   server {
       listen       80; #设置监听地址和端口
       server_name localhost; #设置server name,可以以空格隔开写多个并支持正则表达式,如:*.zhangsan.com www.zhangsan.* ~^www\d+\.zhangsan\.com$ default_server 
        #charset koi8-r; #设置编码格式,默认是俄语格式,建议改为utf-8
        #access_log logs/host.access.log main;
       location / {
           root   html;
           index index.html index.htm;
       }
        #error_page 404             /404.html;
        # redirect server error pages to the static page /50x.html
        #
       error_page   500 502 503 504 /50x.html; #定义错误页面
       location = /50x.html {
           root   html;
       }
        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ { #以http的方式转发php请求到指定web服务器
        #   proxy_pass   http://127.0.0.1;
        #}
        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ { #以fastcgi的方式转发php请求到php处理
        #   root           html;
        #   fastcgi_pass   127.0.0.1:9000;
        #   fastcgi_index index.php;
        #   fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
        #   include       fastcgi_params;
        #}
        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht { #拒绝web形式访问指定文件,如很多的网站都是通过.htaccess文件
来改变自己的重定向等功能。
        #   deny all;
        #}
       location ~ /passwd.html {
           deny all;
       }
   }
    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server { #自定义虚拟server
3.3.1 MIME
范例: 识别php文件为text/html
    #   listen       8000;
    #   listen       somename:8080;
    #   server_name somename alias another.alias;
    #   location / { 
    #       root   html;
    #       index index.html index.htm; #指定默认网页文件,此指令由
ngx_http_index_module模块提供
    #   }
    #}
    # HTTPS server
    #
    #server { #https服务器配置
    #   listen       443 ssl;
    #   server_name localhost;
    #   ssl_certificate     cert.pem;
    #   ssl_certificate_key cert.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;
    #   }
    #}

mime

此项为支持的 文件格式,如果不支持的格式 会自动帮你下载,如果支持 就会显示在网页上

[root@localhost ~]#vim  /etc/nginx/mime.types

types {
    text/html                                        html htm shtml;
    text/css                                         css;
    text/xml                                         xml;
    image/gif                                        gif;
    image/jpeg                                       jpeg jpg;
    application/javascript                           js;
    application/atom+xml                             atom;
    application/rss+xml                              rss;

 
.....................................................................

 application/octet-stream                         bin exe dll;
    application/octet-stream                         deb;
    application/octet-stream                         dmg;
    application/octet-stream                         iso img;
    application/octet-stream                         msi msp msm;

    audio/midi                                       mid midi kar;
    audio/mpeg                                       mp3;
    audio/ogg                                        ogg;
    audio/x-m4a                                      m4a;
    audio/x-realaudio                                ra;

    video/3gpp                                       3gpp 3gp;
    video/mp2t                                       ts;
    video/mp4                                        mp4;
    video/mpeg                                       mpeg mpg;
    video/quicktime                                  mov;
    video/webm                                       webm;
    video/x-flv                                      flv;
    video/x-m4v                                      m4v;
    video/x-mng                                      mng;
    video/x-ms-asf                                   asx asf;
    video/x-ms-wmv                                   wmv;
    video/x-msvideo                                  avi;


sever 下的 root

root指定了主页文件的位置


[root@localhost ~]# vim /apps/nginx/conf/nginx.conf


root路径格式 指定文件的路径    url  

   server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

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


在这里插入图片描述

server块构建虚拟主机

建立独立的配置文件 构建不同虚拟主机 PC端和手机端

基于域名实现,在第一台主nginx服务器中配置文件信息

[root@localhost ~]# systemctl stop firewalld.service && setenforce 0
## 首先需关闭防护墙


[root@localhost ~]# vim /etc/nginx/nginx.conf
#修改配置文件 要放在  http 模块里,如若有直接修改路径即可,并保存退出配置文件
 include             /etc/nginx/mime.types;
 include             /apps/nginx/conf.d/*.conf;

在这里插入图片描述

[root@localhost ~]# cd /apps/nginx/
[root@localhost nginx]# ls
conf  html  logs  run  sbin
[root@localhost nginx]# mkdir conf.d
[root@localhost nginx]# ls
conf  conf.d  html  logs  run  sbin
[root@localhost nginx]# cd conf.d

[root@localhost conf.d]# vim pc.conf
#编写配置文件

server {
   listen  80;
   server_name www.pc.com;
   root /data/nginx/pc/;
}

在这里插入图片描述

[root@localhost conf.d]# cp pc.conf m.conf
[root@localhost conf.d]# vim m.conf
##修改已复制的配置文件
server {
   listen  80;
   server_name www.m.com;
   root /data/nginx/m/;
}


在这里插入图片描述

在这里插入图片描述

[root@localhost conf.d]# cd /
[root@localhost /]# ls
apps  boot  etc   lib    media  opt   root  sbin  sys  usr
bin   dev   home  lib64  mnt    proc  run   srv   tmp  var
[root@localhost /]# mkdir data
[root@localhost /]# cd data
[root@localhost data]# mkdir -p /data/nginx/{pc,m}
#构建数据文件夹

[root@localhost data]# tree
.
└── nginx
    ├── m
    └── pc

3 directories, 0 files


[root@localhost data]# echo pc > nginx/pc/index.html
[root@localhost data]# echo moblie > nginx/m/index.html
#构建数据文件


[root@localhost conf.d]# nginx -t
## 检查语法是否编写有误
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@localhost conf.d]# nginx -s reload
## 重新加载保存配置文件信息

在第二台机器中修改/etc/hosts 文件

在这里插入代码片[root@localhost ~]# systemctl stop firewalld.service && setenforce 0
## 首先需关闭防护墙

[root@localhost ~]# vim /etc/hosts
20.0.0.100 www.pc.com
20.0.0.100 www.m.com


==================================
[root@localhost ~]# ifconfig ens33
###使用此命令可查机器中的ip地址

==================================

在这里插入图片描述

[root@localhost ~]# curl www.pc.com
pc
[root@localhost ~]# curl www.m.com
moblie

基于ip地址实现,修改监听地址

[root@localhost data]# vim /apps/nginx/conf.d/pc.conf

server {
   listen  20.0.0.100:80;     #主nginx服务器中的ip地址
   server_name www.pc.com;
   root /data/nginx/pc/;
}


[root@localhost data]# vim /apps/nginx/conf.d/pc.conf

server {
   listen  20.0.0.111:80;  #没有这个ip地址,需创建虚拟网卡
   server_name www.m.com;
   root /data/nginx/m/;
}

[root@localhost data]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@localhost data]# nginx -s reload


[root@localhost data]# ifconfig ens33:0 20.0.0.111/24
### 添加虚拟网卡IP地址

[root@localhost data]# ping 20.0.0.111   
##检测是否能ping通

PING 20.0.0.111 (20.0.0.111) 56(84) bytes of data.
64 bytes from 20.0.0.111: icmp_seq=1 ttl=64 time=0.021 ms
64 bytes from 20.0.0.111: icmp_seq=2 ttl=64 time=0.077 ms
64 bytes from 20.0.0.111: icmp_seq=3 ttl=64 time=0.076 ms
^C
--- 20.0.0.111 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2004ms
rtt min/avg/max/mdev = 0.021/0.058/0.077/0.026 ms


[root@localhost data]# ifconfig 
## 20.0.0.10020.0.0.111网卡都有了

ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 20.0.0.100  netmask 255.255.255.0  broadcast 20.0.0.255
        inet6 fe80::dd61:d740:5b3f:7961  prefixlen 64  scopeid 0x20<link>
        ether 00:0c:29:f3:23:63  txqueuelen 1000  (Ethernet)
        RX packets 98391  bytes 141396302 (134.8 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 46312  bytes 2950909 (2.8 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

ens33:0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 20.0.0.111  netmask 255.255.255.0  broadcast 20.0.0.255
        ether 00:0c:29:f3:23:63  txqueuelen 1000  (Ethernet)

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1  (Local Loopback)
        RX packets 1382  bytes 223550 (218.3 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 1382  bytes 223550 (218.3 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

virbr0: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        inet 192.168.122.1  netmask 255.255.255.0  broadcast 192.168.122.255
        ether 52:54:00:56:af:51  txqueuelen 1000  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

在这里插入图片描述

到第二台机器中测试

[root@localhost ~]# curl 20.0.0.100
pc
[root@localhost ~]# curl 20.0.0.111
moblie

在这里插入图片描述

基于端口实现,只改端口不改ip地址

[root@localhost data]# cd /apps/nginx/conf.d
[root@localhost conf.d]# ls
m.conf  pc.conf

[root@localhost conf.d]# vim pc.conf


server {
   listen  20.0.0.100:8080;
   server_name www.pc.com;
   root /data/nginx/pc/;
}

在这里插入图片描述


[root@localhost conf.d]# vim m.conf


server {
   listen  20.0.0.100:9527;
   server_name www.m.com;
   root /data/nginx/m/;
}

在这里插入图片描述

[root@localhost conf.d]# ifconfig ens33:0 down
### 禁用刚刚弄的虚拟网卡20.0.0.111 

[root@localhost conf.d]# ifconfig
ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 20.0.0.100  netmask 255.255.255.0  broadcast 20.0.0.255
        inet6 fe80::dd61:d740:5b3f:7961  prefixlen 64  scopeid 0x20<link>
        ether 00:0c:29:f3:23:63  txqueuelen 1000  (Ethernet)
        RX packets 98592  bytes 141415239 (134.8 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 46475  bytes 2970645 (2.8 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1  (Local Loopback)
        RX packets 1382  bytes 223550 (218.3 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 1382  bytes 223550 (218.3 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

virbr0: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        inet 192.168.122.1  netmask 255.255.255.0  broadcast 192.168.122.255
        ether 52:54:00:56:af:51  txqueuelen 1000  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

在这里插入图片描述

[root@localhost conf.d]# nginx -t
## 检查语法输入是否有误
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@localhost conf.d]# nginx -s reload
## 重新加载配置文件信息

到第二台机器中测试

[root@localhost ~]# curl 20.0.0.100:8080
pc
[root@localhost ~]# curl 20.0.0.100:9527
moblie

在这里插入图片描述

alias 别名

别名设置

server {
   listen 80;
   server_name www.pc.com;
   location /nwes {
        root /data/nginx/html/pc/;
        #相当于追加  将 文件夹news追加到/data/nginx/html/pc/news
        }
   location /study{
        alias /mnt/nginx/sports/;
        #相当于替换 你访问 study  就是访问/mnt/nginx/sports
        }
}

location

在一个server中location配置段可存在多个,用于实现从uri到文件系统的路径映射;ngnix会根据用户请求的URI来检查定义的所有location,按一定的优化级找出一个最佳匹配,而后应用其配置在没有使用正则表达式的时候,nginx会先在server中的多个location选取匹配度最高的一个uri,uri是用户请求的字符串,即域名后面的web文件路径,然后使用该location模块中的正则url和字符串,如果匹配成功就结束搜索,并使用此location处理此请求。

location 官方帮助:

http://nginx.org/en/docs/http/ngx_http_core_module.html#location

语法规则

#语法规则:
location [ = | ~ | ~* | ^~ ] uri { ... }

=              	#用于标准uri前,需要请求字串与uri精确匹配,大小敏感,如果匹配成功就停止向下匹配并立即处理请求
^~            	#用于标准uri前,表示包含正则表达式,并且匹配以指定的正则表达式开头,对URI的最左边部分做匹配检查,不区分字符大小写
~              	#用于标准uri前,表示包含正则表达式,并且区分大小写
~*            	#用于标准uri前,表示包含正则表达式,并且不区分大写
不带符号   	  	 #匹配起始于此uri的所有的uri
 \             	#用于标准uri前,表示包含正则表达式并且转义字符。可以将 . * ?等转义为普通符号

#匹配优先级从高到低:
=, ^~, ~/~*, 不带符号






location = / {
   [ configuration A ]
}
location / {
   [ configuration B ]
}
location /documents/ {
   [ configuration C ]
}
location ^~ /images/ {
   [ configuration D ]
}
location ~* \.(gif|jpg|jpeg)$ {
   [ configuration E ]
}
The/” request will match configuration A(?), the “/index.html” request will match configuration B,
the “/documents/document.html” request will match configuration C, 
the “/images/1.gif” request will match configuration D, 
and the “/documents/1.jpg” request will match configuration E.
  1. = 用于标准uri前,需要请求字串与uri精确匹配,大小敏感,如果匹配成功就停止向下匹配并立即处理请求
  2. ^~ 用于标准uri前,表示包含正则表达式,并且匹配以指定的正则表达式开头,对URI的最左边部分做匹配检查,不区分字符大小写
  3. ~ 用于标准uri前,表示包含正则表达式,并且区分大小写
  4. ~* 用于标准uri前,表示包含正则表达式,并且不区分大写
  5. 不带符号 匹配起始于此uri的所有的uri
  6. \ 用于标准uri前,表示包含正则表达式并且转义字符。可以将 . * ?等转义为普通符号

不区分大小写-案例

~* 用来对用户请求的uri做模糊匹配,uri中无论都是大写、都是小写或者大小写混合,此模式也都会匹配,通常使用此模式匹配用户request中的静态资源并继续做下一步操作,此方式使用较多注意: 此方式中,对于Linux文件系统上的文件仍然是区分大小写的,如果磁盘文件不存在,仍会提示404 ~* 虽然 不区分大小写 但是系统的文件系统区分大小写

#正则表达式匹配:
 location ~* /A.?\.jpg {
  #匹配 已A后面一个或没有字符,已.jpg结尾的图片
   root /opt/nginx/html/image;
 }
 
 
只要是图片就去 images中找
server{
location ~* \.(gif|jpg|jpeg|bmp|png|tiff|tif|ico|wmf|js|css)$ {
        root /data/nginx/images/;
 }
}

生产案例

#直接匹配网站根会加速Nginx访问处理
location = /index.html {
   ......;
}
location / {
   ......;
}
#静态资源配置方法1
location ^~ /static/ {
   ......;
}
#静态资源配置方法2,应用较多
location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ {
   ......;
}
#多应用配置
location ~* /app1 {
     ......;
}
location ~* /app2 {
     ......;
}

access 模块 四层控制

如何查看模块是否默认安装

http://nginx.org/en/docs/http/ngx_http_access_module.html

[root@localhost nginx-1.18.0]#./configure --help |grep access
# 可以去源码包中 过滤  access模块  自带 不想要可以 without 去掉 
  --without-http_access_module       disable ngx_http_access_module
  --http-log-path=PATH               set http access log pathname
  --without-stream_access_module     disable ngx_stream_access_module

在这里插入图片描述

验证模块

配置
server {
   listen 80;
   server_name www.kgc.com;
   location / {
        root /data/nginx/html/pc;
 }
   location /admin{
        root /data/nginx/html/pc;
        auth_basic    "admin site";
        #提示信息,不是所有浏览器都有用
        auth_basic_user_file /apps/nginx/conf.d/.httpuser;
        #密码文件存放位置
 }
}


[root@localhost conf.d]#htpasswd -bc /apps/nginx/conf.d/.httpuser kgc 123456
#没有  yum install  httpd-tools
Adding password for user kgc
[root@localhost conf.d]#cat /apps/nginx/conf.d/.httpuser 
kgc:$apr1$RtjFE23R$lf2n.YpdssSf1EYJbIDqT0

自定义 错误页面

可以改变 默认的错误页面

server {
   listen 80;
   server_name www.kgc.com;
   root /data/nginx/html/pc;
   error_page 404 /40x.html;
   #当出现404 错误  就去  root /data/nginx/html/pc/error/ 这个文件夹找40x.html  这个文件
   location = /40x.html {
        root /data/nginx/html/pc/error/;
 }
   location / {
        root /data/nginx/html/pc;
 }
   location /admin{
        auth_basic    "admin site";
        auth_basic_user_file /apps/nginx/conf.d/.httpuser;
 }
}


自定义 错误码
server {
   listen 80;
   server_name www.kgc.com;
   root /data/nginx/html/pc;
   error_page 404 =302 /40x.html;
   #把错误码 404 指定成302
   location = /40x.html {
        root /data/nginx/html/pc/error/;
 }
   location / {
        root /data/nginx/html/pc;
 }
   location /admin{
        auth_basic    "admin site";
        auth_basic_user_file /apps/nginx/conf.d/.httpuser;
 }
}




#出了错  直接跳转到显示主站点
server {
   listen 80;
   server_name www.kgc.com;
   root /data/nginx/html/pc;
   error_page 404 =302 /index.html;
   #把错误码 404 指定成302  并跳到主页面:/index.html
   location = /40x.html {
        root /data/nginx/html/pc/error/;
 }

日志位置存放

Syntax: error_log file [level];
#格式  error_log   文件路径    级别(info  debug等  可以忽略不写)
Default: 
error_log logs/error.log error;
Context: main, http, mail, stream, server, location
level: debug, info, notice, warn, error, crit, alert, emerg



[root@localhost ~]# mkdir /data/nginx/logs
 listen 80;
 server_name www.kgc.org;
 error_page  500 502 503 504 404 /error.html; 
 access_log /apps/nginx/logs/kgc_access.log; 
 error_log /apps/nginx/logs/kgc_error.log; 
 #定义错误日志文件
 location = /error.html {
   root   html;
 }
#重启nginx并访问不存在的页面进行测试并验证是在指定目录生成新的日志文件


[root@localhost ~]#mkdir /apps/nginx/logs
[root@localhost ~]#nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@localhost ~]#nginx -s reload

检测文件是否存在

try_files会按顺序检查文件是否存在,返回第一个找到的文件或文件夹(结尾加斜线表示为文件夹),如果所有文件或文件夹都找不到,会进行一个内部重定向到最后一个参数。只有最后一个参数可以引起一个内部重定向,之前的参数只设置内部URI的指向。最后一个参数是回退URI且必须存在,否则会出现内部500错误。

Syntax: try_files file ... uri;
try_files file ... =code;
Default:Context: server, location


location / {
   root /data/nginx/html/pc;
   index index.html;
   try_files $uri  $uri.html $uri/index.html /about/default.html;
    #try_files $uri $uri/index.html $uri.html =489;
}
[root@centos8 ~]# echo "default page" >> /data/nginx/html/pc/about/default.html
#重启nginx并测试,当访问到http://www.kgc.org/about/xx.html等不存在的uri会显示default.html,如果是自定义的状态码则会显示在返回数据的状态码中
#注释default.html行,启用上面489行生效后,再观察结果
[root@centos8 ~]# curl -I http://www.kgc.org/about/xx.html
HTTP/1.1 489 #489就是自定义的状态返回码
Server: nginx
Date: Thu, 21 Feb 2019 00:11:40 GMT
Content-Length: 0
Connection: keep-alive
Keep-Alive: timeout=65

例子 解释
#一定要有兜底否则也还是报错 我测试的结果   kgc.html是兜底的可能版本不一
location / {
        root /data/nginx/html/pc;
        try_files $uri  $uri.html $uri/index.html /about/default.html;
        #你如果 访问一个路径 /kgc   如果没有这个页面   先去找kgc  kgc.html  然后再去找 kgc/index.html    最后再                           找/about/default.html         
 }

长连接

A如何测试是否打开长连接

[root@localhost ~]#yum install telnet
#安装命令


keepalive_timeout timeout [header_timeout];  #设定保持连接超时时长,0表示禁止长连接,默认为75s,通常配置在http字段作为站点全局配置
keepalive_requests number;  #在一次长连接上所允许请求的资源的最大数量,默认为100,建议适当调大,比如:500

可以加在全局或者 server 

keepalive_requests 3;
#最大三个连接
keepalive_timeout 60 65;   #只能由一个空格 
#开启长连接后,返回客户端的会话保持时间为60s,单次长连接累计请求达到指定次数请求或65秒就会被断开,后面的60为发送给客户端应答报文头部中显示的超时时间设置为60s:如不设置客户端将不显示超时时间。
Keep-Alive:timeout=60  #浏览器收到的服务器返回的报文
#如果设置为0表示关闭会话保持功能,将如下显示:
Connection:close  #浏览器收到的服务器返回的报文
#使用命令测试:
[root@centos8 ~]# telnet www.kgc.org 80
Trying 10.0.0.8...
Connected to www.kgc.org.
Escape character is '^]'.
GET / HTTP/1.1
HOST: www.kgc.org
#Response Headers(响应头信息):
HTTP/1.1 200 OK
Server: nginx/1.18.0
Date: Thu, 24 Sep 2020 04:35:35 GMT
Content-Type: text/html
Content-Length: 7
Last-Modified: Wed, 23 Sep 2020 14:39:21 GMT
Connection: keep-alive
Keep-Alive: timeout=60
ETag: "5c8a6b3a-7"
Accept-Ranges: bytes
#页面内容
pc web

B 对哪种浏览器禁用长连接

keepalive_disable none | browser ...;  
#对哪种浏览器禁用长连接

作为下载服务器配置

本地yum http apache ftp 本地

[root@localhost nginx-1.18.0]#./configure --help |grep auto
#自带
  --without-http_autoindex_module    disable ngx_http_autoindex_module
  
autoindex on | off;
#自动文件索引功能,默为off
autoindex_exact_size on | off;  
#计算文件确切大小(单位bytes),off 显示大概大小(单位KM),默认on
autoindex_localtime on | off ; 
#显示本机时间而非GMT(格林威治)时间,默认off
autoindex_format html | xml | json | jsonp; 
#显示索引的页面文件风格,默认html
limit_rate rate; 
#限制响应客户端传输速率(除GET和HEAD以外的所有方法),单位B/s,即bytes/second,默认值0,表示无限制,此指令由ngx_http_core_module提供
set $limit_rate
#变量提供 限制   变量优先级高




[root@centos8 ~]# mkdir  /opt/download
#注意:download不需要index.html文件


location /download {
       autoindex on;
       #开启下载服务器
       autoindex_exact_size on;
       #开启确切大小不建议开启
       autoindex_localtime on;
       #使用当地时间
       limit_rate 1024k;
       #所有人限速1024k,默认单位是字节数
       set $limit_rate 2M;
       #谁先生效
       alias /opt/download;
  }


直接访问页面

location /download {
       autoindex on;
       autoindex_exact_size on;
       autoindex_localtime on;
       limit_rate 1024k;
       alias /opt/download;
  }

用户上传资料

上传需要借助开发小的程序, 并且程序和 nginx都会限制。 两者取最小

client_max_body_size 1m; 
#设置允许客户端上传单个文件的最大值,默认值为1m,上传文件超过此值会出413错误
client_body_buffer_size size; 
#用于接收每个客户端请求报文的body部分的缓冲区大小;默认16k;超出此大小时,其将被暂存到磁盘上的由下面client_body_temp_path指令所定义的位置
client_body_temp_path path [level1 [level2 [level3]]];
#设定存储客户端请求报文的body部分的临时存储路径及子目录结构和数量,目录名为16进制的数字,使用hash之后的值从后往前截取1位、2位、2位作为目录名

上传文件大于限制  错误代码413

其他设置

buffer cache

directio size | off; #操作完全和aio相反,aio是读取文件而directio是写文件到磁盘,启用直接I/O,默认为关闭,当文件大于等于给定大小时,例如:directio 4m;同步(直接)写磁盘,而非写缓存。


open_file_cache off;  #是否缓存打开过的文件信息
open_file_cache max=N [inactive=time];
#nginx可以缓存以下三种信息:
(1) 文件元数据:文件的描述符、文件大小和最近一次的修改时间
(2) 打开的目录结构
(3) 没有找到的或者没有权限访问的文件的相关信息 
max=N:#可缓存的缓存项上限数量;达到上限后会使用LRU(Least recently used,最近最少使用)算法实现管理
inactive=time:#缓存项的非活动时长,在此处指定的时长内未被命中的或命中的次数少于



open_file_cache_min_uses指令所指定的次数的缓存项即为非活动项,将被删除 
open_file_cache_valid time; #缓存项有效性的检查验证频率,默认值为60s 
open_file_cache_errors on | off; #是否缓存查找时发生错误的文件一类的信息,默认值为off
open_file_cache_min_uses number; #open_file_cache指令的inactive参数指定的时长内,至少
被命中此处指定的次数方可被归类为活动项,默认值为1

范例:
open_file_cache max=10000 inactive=60s; #最大缓存10000个文件,非活动数据超时时长60s
open_file_cache_valid   60s;  #每间隔60s检查一下缓存数据有效性
open_file_cache_min_uses 5; #60秒内至少被命中访问5次才被标记为活动数据
open_file_cache_errors   on; #缓存错误信息



limit_except method ... { ... },仅用于location
#限制客户端使用除了指定的请求方法之外的其它方法 
method:GET, HEAD, POST, PUT, DELETE,MKCOL, COPY, MOVE, OPTIONS, PROPFIND, 
PROPPATCH, LOCK, UNLOCK, PATCH
limit_except GET {
 allow 192.168.0.0/24;
 allow 10.0.0.1;
 deny all;
}#除了GET和HEAD 之外其它方法仅允许192.168.1.0/24网段主机使用

高级配置

网页的状态页

基于nginx 模块 ngx_http_stub_status_module 实现,在编译安装nginx的时候需要添加编译参数 --with-http_stub_status_module,否则配置完成之后监测会是提示语法错误注意: 状态页显示的是整个服务器的状态,而非虚拟主机的状态

#配置示例:
location /nginx_status {
   #stub_status;
   auth_basic           "auth login";
   auth_basic_user_file /apps/nginx/conf/.htpasswd;
   allow 192.168.0.0/16;
   allow 127.0.0.1;
   deny all;
 }
#状态页用于输出nginx的基本状态信息:
#输出信息示例:
Active connections: 291
server accepts handled requests
 16630948 16630948 31070465
 上面三个数字分别对应accepts,handled,requests三个值
Reading: 6 Writing: 179 Waiting: 106
Active connections: #当前处于活动状态的客户端连接数,包括连接等待空闲连接数=reading+writing+waiting
accepts:#统计总值,Nginx自启动后已经接受的客户端请求的总数。
handled:#统计总值,Nginx自启动后已经处理完成的客户端请求总数,通常等于accepts,除非有因worker_connections限制等被拒绝的连接
requests:#统计总值,Nginx自启动后客户端发来的总的请求数。
Reading:#当前状态,正在读取客户端请求报文首部的连接的连接数,数值越大,说明排队现象严重,性能不足
Writing:#当前状态,正在向客户端发送响应报文过程中的连接数,数值越大,说明访问量很大
Waiting:#当前状态,正在等待客户端发出请求的空闲连接数,开启 keep-alive的情况下,这个值等于active – (reading+writing)

while : ;do ab -c 1000 -n 10000 http://192.168.91.100/;sleep 1;done
#压力测试

[root@localhost ~]#curl http://www.kgc.com/nginx_status 2>/dev/null  |awk '/Reading/{print  $2,$4,$6}'
#
[root@localhost ~]#curl http://用户名:密码@www.kgc.com/nginx_status 2>/dev/null  |awk '/Reading/{print  $2,$4,$6}'

#curl http://www.pc.com/status 2> /dev/null |awk '/Reading/{print $2,$4,$6}'


Nginx 第三方模块

ehco 模块

开源的echo模块 https://github.com/openresty/echo-nginx-module

location  /ip {
  default_type   text/html;
  echo "welcome, your ip addr: ";
  echo $remote_addr;
}

[root@localhost opt]#yum install git -y
#安装git
[root@localhost opt]#git clone https://github.com/openresty/echo-nginx-module.git


./configure --prefix=/apps/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 --add-module=/opt/echo-nginx-module-master

make && make install

[root@localhost ~]#nginx -t
nginx: [emerg] unknown directive "echo" in /apps/nginx/conf.d/pc.conf:26
nginx: configuration file /apps/nginx/conf/nginx.conf test failed
 
[root@localhost nginx-1.18.0]#ll /apps/nginx/sbin/
总用量 15808
-rwxr-xr-x. 1 root  root  8407568 219 15:35 nginx
-rwxr-xr-x. 1 nginx nginx 7774624 214 17:02 nginx.old


[root@localhost nginx-1.18.0]#nginx -t
nginx: the configuration file /apps/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /apps/nginx/conf/nginx.conf test is successful

[root@localhost nginx-1.18.0]#systemctl stop nginx
[root@localhost nginx-1.18.0]#systemctl start nginx


location  /hello {
  default_type   text/html;
  echo "hello world ";
}

变量

http://nginx.org/en/docs/varindex.html
官方文档

内置

常用内置变量

$remote_addr; 
#存放了客户端的地址,注意是客户端的公网IP
$proxy_add_x_forwarded_for
#此变量表示将客户端IP追加请求报文中X-Forwarded-For首部字段,多个IP之间用逗号分隔,如果请求中没有X-Forwarded-For,就使用$remote_addrthe “X-Forwarded-For” client request header field with the $remote_addr variable appended to it, separated by a comma. If the “X-Forwarded-For” field is not present in the client request header, the $proxy_add_x_forwarded_for variable is equal to the $remote_addr variable.
客户机    代理1     代理2     nginx服务器
$proxy_add_x_forwarded_for: 在代理1 上存的是  客户机的ip
$proxy_add_x_forwarded_for: 在代理2 上存的是  客户机的ip,代理1的ip            用逗号隔开
$proxy_add_x_forwarded_for: nginx  上存的是  客户机的ip,代理1的ip,代理2的ip



$args; 
#变量中存放了URL中的参数,例如:http://www.kgc.org/main/index.do?id=20190221&partner=search
#返回结果为: id=20190221&partner=search    存放的就是这个


$document_root; 
#保存了针对当前资源的请求的系统根目录,例如:/apps/nginx/html。



$document_uri; #保存了当前请求中不包含参数的URI,注意是不包含请求的指令,比
如:http://www.kgc.org/main/index.do?id=20190221&partner=search会被定义为/main/index.do 
#返回结果为:/main/index.do


$host; 
#存放了请求的host名称


limit_rate 10240;
echo $limit_rate; #如果nginx服务器使用limit_rate配置了显示网络速率,则会显示,如果没有设置, 则显示0


$remote_port; #客户端请求Nginx服务器时随机打开的端口,这是每个客户端自己的端口

$remote_user; #已经经过Auth Basic Module验证的用户名

$request_body_file; #做反向代理时发给后端服务器的本地资源的名称

$request_method; #请求资源的方式,GET/PUT/DELETE等

$request_filename; #当前请求的资源文件的磁盘路径,由root或alias指令与URI请求生成的文件绝对路径,如:/apps/nginx/html/main/index.html

$request_uri; #包含请求参数的原始URI,不包含主机名,相当于:$document_uri?$args,例如:/main/index.do?id=20190221&partner=search 

$scheme; #请求的协议,例如:http,https,ftp等

$server_protocol; #保存了客户端请求资源使用的协议的版本,例如:HTTP/1.0,HTTP/1.1,HTTP/2.0等

$server_addr; #保存了服务器的IP地址

$server_name; #请求的服务器的主机名

$server_port; #请求的服务器的端口号

$http_<name>
#name为任意请求报文首部字段,表示记录请求报文的首部字段
arbitrary request header field; the last part of a variable name is the field name converted to lower case with dashes replaced by underscores 
#用下划线代替横线
#示例: echo $http_User_Agent;  


$http_user_agent; #客户端浏览器的详细信息

$http_cookie; #客户端的cookie信息


$cookie_<name>
#name为任意请求报文首部字部cookie的key名


 location /main {
index index.html;
default_type text/html;
echo "hello world,main-->";
echo $remote_addr;
echo $args;
echo $document_root;
echo $document_uri;
echo $host;
echo $http_user_agent;
echo $http_cookie;
echo $request_filename;
echo $scheme;
echo $scheme://$host$document_uri?$args;
}

在这里插入图片描述

自定义变量

假如需要自定义变量名称和值,使用指令set $variable value;

语法格式:

Syntax: set $variable value;
Default:Context: server, location, if

示例:

set $name kgc;
echo $name;
set $my_port $server_port;
echo $my_port;
echo "$server_name:$server_port"; #输出信息如下
[root@centos6 ~]#curl www.kgc.org/main
kgc
80
www.kgc.org:80

自定义访问日志

日志的格式 可以自由指定

log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"'
                      '$server_name:$server_port';


log_format  test  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"'
                      '$server_name:$server_port';

格式可以定义多个

###注意如果开启 include  注意定义自配置文件与 日志格式的上下关系  ,   日志格式一定要在  include 之前 否则会不生效。


自定义json 格式日志

方便ELK收集日志

log_format access_json '{"@timestamp":"$time_iso8601",'
        '"host":"$server_addr",'
        '"clientip":"$remote_addr",'
        '"size":$body_bytes_sent,'
        '"responsetime":$request_time,'
        '"upstreamtime":"$upstream_response_time",'
        '"upstreamhost":"$upstream_addr",'  
        '"http_host":"$host",'
        '"uri":"$uri",'
        '"xff":"$http_x_forwarded_for",'
        '"referer":"$http_referer",'
        '"tcp_xff":"$proxy_protocol_addr",'
        '"http_user_agent":"$http_user_agent",'
        '"status":"$status"}';


location / {
  root /data/nginx/pc/;
  access_log logs/access.log access_json;
}


'"http_user_agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTMLe/101.0.4951.54 Safari/537.36",'    '"status":"304"}'

cat /var/log/nginx/access.log |sed -r 's/.*(status)":"(.*)"}.*/\2/'

利用脚本分析返回码
[root@localhost ~]#cat /var/log/nginx/access.log |sed -r 's/.*(status)":"(.*)"}.*/\2/'|sort -n|uniq -c
#统计状态码个数
      6 200
     26 304
     28 404




cat /var/log/nginx/access.log |awk -F: '{print $6}'|sed -r 's/"(.*)",.*/\1/'
利用脚本提取ip地址




#!/usr/bin/env python3
#coding:utf-8
status_200= []
status_404= []
with open("access_json.log") as f:
    for line in f.readlines():
        line = eval(line)
        if line.get("status") == "200":
            status_200.append(line.get)
        elif line.get("status") == "404":
            status_404.append(line.get)
        else:
            print("状态码 ERROR")
        print((line.get("clientip")))
f.close()
print("状态码200的有--:",len(status_200))
print("状态码404的有--:",len(status_404))

Nginx压缩功能

支持对指定类型的文件进行压缩然后再传输给客户端,而且压缩还可以设置压缩比例,压缩后的文件大小将比源文件显著变小,这样有助于降低出口带宽的利用率,降低企业的IT支出,不过会占用相应的CPU资源。Nginx对文件的压缩功能是依赖于模块 ngx_http_gzip_module

官方文档: https://nginx.org/en/docs/http/ngx_http_gzip_module.html

配置指令如下:

#启用或禁用gzip压缩,默认关闭
gzip on | off; 
#压缩比由低到高从19,默认为1
gzip_comp_level level;
#禁用IE6 gzip功能
gzip_disable "MSIE [1-6]\."; 
#gzip压缩的最小文件,小于设置值的文件将不会压缩
gzip_min_length 1k; 
#启用压缩功能时,协议的最小版本,默认HTTP/1.1
gzip_http_version 1.0 | 1.1; 
#指定Nginx服务需要向服务器申请的缓存空间的个数和大小,平台不同,默认:32 4k或者16 8k;
gzip_buffers number size;  
#指明仅对哪些类型的资源执行压缩操作;默认为gzip_types text/html,不用显示指定,否则出错
gzip_types mime-type ...; 
#如果启用压缩,是否在响应报文首部插入“Vary: Accept-Encoding,一般建议打开
gzip_vary on | off;
#预压缩
gzip_static on | off;


#重启nginx并进行访问测试压缩功能
[root@centos8 ~]# cp /apps/nginx/logs/access.log /data/nginx/html/pc/m.txt
[root@centos8 ~]# echo "test" > /data/nginx/html/pc/test.html #小于1k的文件测试是否
会压缩
[root@centos8 ~]# vim /apps/nginx/conf/nginx.conf
gzip on;


gzip_comp_level 5;
gzip_min_length 1k;
gzip_types text/plain application/javascript application/x-javascript text/css 
application/xml text/javascript application/x-httpd-php image/gif image/png;   
gzip_vary on;
#重启Nginx并访问测试:
[root@centos8 ~]# curl --head --compressed 192.168.91.100/test.html
HTTP/1.1 200 OK
Server: nginx
Date: Fri, 22 Feb 2019 01:52:23 GMT
Content-Type: text/html
Last-Modified: Thu, 21 Feb 2019 10:31:18 GMT
Connection: keep-alive
Keep-Alive: timeout=65
Vary: Accept-Encoding
ETag: W/"5c6e7df6-171109"
Content-Encoding: gzip #压缩传输
#验证不压缩访问的文件大小:

实际操作

太小的文件没必要压缩,压缩说不定变大了

server {
        listen       80;
        listen       [::]:80;
        server_name  _;
        root         /usr/share/nginx/html;
        gzip on;
        gzip_comp_level 9;
        gzip_min_length 1k;
        gzip_vary on;

https 功能

Web网站的登录页面都是使用https加密传输的,加密数据以保障数据的安全,HTTPS能够加密信息,以免敏感信息被第三方获取,所以很多银行网站或电子邮箱等等安全级别较高的服务都会采用HTTPS协议,HTTPS其实是有两部分组成:HTTP + SSL / TLS,也就是在HTTP上又加了一层处理加密信息的模块。服务端和客户端的信息传输都会通过TLS进行加密,所以传输的数据都是加密后的数据。

在这里插入图片描述

nginx 的https 功能基于模块ngx_http_ssl_module实现,因此如果是编译安装的nginx要使用参数ngx_http_ssl_module开启ssl功能,但是作为nginx的核心功能,yum安装的nginx默认就是开启的,编译安装的nginx需要指定编译参数–with-http_ssl_module开启

官方文档:

https://nginx.org/en/docs/http/ngx_http_ssl_module.html

参数 https

listen 443 ssl;
#为指定的虚拟主机配置是否启用ssl功能,此功能在1.15.0废弃,使用listen [ssl]替代
ssl_certificate /path/to/file;
#指向包含当前虚拟主机和CA的两个证书信息的文件,一般是crt文件
ssl_certificate_key /path/to/file;
#当前虚拟主机使用的私钥文件,一般是key文件
ssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2]; 
#支持ssl协议版本,早期为ssl现在是TLS,默认为后三个
ssl_session_cache off | none | [builtin[:size]] [shared:name:size];
#配置ssl缓存
   off: #关闭缓存
 none:  #通知客户端支持ssl session cache,但实际不支持
 builtin[:size]:#使用OpenSSL内建缓存,为每worker进程私有
 [shared:name:size]:#在各worker之间使用一个共享的缓存,需要定义一个缓存名称和缓存空间
大小,一兆可以存储4000个会话信息,多个虚拟主机可以使用相同的缓存名称
ssl_session_timeout time;
#客户端连接可以复用ssl session cache中缓存的有效时长,默认5m

自签名证书

server {
 listen 80;
 listen 443 ssl;
 ssl_certificate /apps/nginx/conf.d/ssl/www.kgc.com.crt;
 ssl_certificate_key /apps/nginx/conf.d/ssl/www.kgc.com.key;
 ssl_session_cache shared:sslcache:20m;
 ssl_session_timeout 10m;
}

自定义图标

favicon.ico 文件是浏览器收藏网址时显示的图标,当客户端使用浏览器问页面时,浏览器会自己主动发起请求获取页面的favicon.ico文件,但是当浏览器请求的favicon.ico文件不存在时,服务器会记录404日志,而且浏览器也会显示404报错

#方法一:服务器不记录访问日志:
location = /favicon.ico {
   log_not_found off;
   access_log off;
}
#方法二:将图标保存到指定目录访问:
#location ~ ^/favicon\.ico$ {
location = /favicon.ico {
     root   /data/nginx/html/pc/images;
     expires 365d;  #设置文件过期时间
}


重写功能

Nginx服务器利用 ngx_http_rewrite_module 模块解析和处理rewrite请求,此功能依靠 PCRE(perl compatible regular expression),因此编译之前要安装PCRE库,rewrite是nginx服务器的重要功能之

一,用于实现URL的重写,URL的重写是非常有用的功能,比如它可以在我们改变网站结构之后,不需要客户端修改原来的书签,也无需其他网站修改我们的链接,就可以设置为访问,另外还可以在一定程度上提高网站的安全性。

ngx_http_rewrite_module模块指令

官方文档:

https://nginx.org/en/docs/http/ngx_http_rewrite_module.html

if指令

官方文档:

https://nginx.org/en/docs/http/ngx_http_rewrite_module.html#if

用于条件匹配判断,并根据条件判断结果选择不同的Nginx配置,可以配置在server或location块中进行配置,Nginx的if语法仅能使用if做单次判断,不支持使用if else或者if elif这样的多重判断,用法如下:

if (条件匹配) { 
 action
}

使用正则表达式对变量进行匹配,匹配成功时if指令认为条件为true,否则认为false,变量与表达式之间使用以下符号链接:

= #比较变量和字符串是否相等,相等时if指令认为该条件为true,反之为false
!=  #比较变量和字符串是否不相等,不相等时if指令认为条件为true,反之为false
~ #区分大小写字符,可以通过正则表达式匹配,满足匹配条件为真,不满足匹配条件为假
!~ #区分大小写字符,判断是否匹配,不满足匹配条件为真,满足匹配条件为假

~* #不区分大小写字符,可以通过正则表达式匹配,满足匹配条件为真,不满足匹配条件为假
!~* #不区分大小字符,判断是否匹配,满足匹配条件为假,不满足匹配条件为真


-f 和 !-f #判断请求的文件是否存在和是否不存在
-d 和 !-d #判断请求的目录是否存在和是否不存在
-x 和 !-x #判断文件是否可执行和是否不可执行
-e 和 !-e #判断请求的文件或目录是否存在和是否不存在(包括文件,目录,软链接)
#注意:
#如果$变量的值为空字符串或0,则if指令认为该条件为false,其他条件为true。
#nginx 1.0.1之前$变量的值如果以0开头的任意字符串会返回false
#示例:
http://www.baidu.com

3字打头重定向
301  永久重定向  将缓存记录在浏览器中
302  临时重定向  没有缓存  每次都要重定向 
304  


location /main {
     index index.html;
     default_type text/html;
     if ( $scheme = http ){
       echo "if-----> $scheme";
     }
     if ( $scheme = https ){
      echo "if ----> $scheme";
   }
    
     #if (-f $request_filename) {
     #   echo "$request_filename is exist";
     #}
     if (!-e $request_filename) {
        echo "$request_filename is not exist";
        #return ;
   }
 }

return

return用于完成对请求的处理,并直接向客户端返回响应状态码,比如:可以指定重定向URL(对于特殊重定向状态码,301/302等) 或者是指定提示文本内容(对于特殊状态码403/500等),处于此指令后的所有配置都将不被执行,return可以在server、if 和 location块进行配置

语法格式:

www.kgc.com/test/
404
return code; #返回给客户端指定的HTTP状态码
return code [text]; #返回给客户端的状态码及响应报文的实体内容,可以调用变量,其中text如果有空格,需要用单或双引号
return code url; #返回给客户端的URL地址    

示例:

location / {
   root /data/nginx/html/pc;
    default_type text/html;
   index index.html;
      if ( $scheme = http ){
        #return 666;
        #return 666 "not allow http";
        #return 301 http://www.baidu.com;
       return 500 "service error";
        echo "if-----> $scheme"; #return后面的将不再执行
     }
     if ( $scheme = https ){
      echo "if ----> $scheme";
   }
}

例子1:
server { 
    listen 80;
    server_name www.kgc.com;
    root /data/nginx/pc/;
	location /{
        root /data/nginx/pc/;

}
  location /test {      #访问test 直接返回403
	return 403;         #可以改成666    
  }

}

例子2:
location /test {                #访问test 直接返回403
	return 666 "hello";         #可以改成666自定义,hello是描述 文字可以  图形浏览器不可以    
  }


例子3:
  location /test { 
  default_type text/plain;     #定义文本格式后图形浏览器可以看见
  return 666 "hello";
 } 


例子4:
location /test {
        default_type text/plain;
        return 302 http://www.baidu.com;    
}

301 缓存在磁盘上,有些
302 没有缓存 , 服务器断开无法重定向   jd

永久重定向
在这里插入图片描述

set指令

指定key并给其定义一个变量,变量可以调用Nginx内置变量赋值给key,另外set定义格式为set $key value,value可以是text, variables和两者的组合。

location /main {
   root /data/nginx/html/pc;
   index index.html;
   default_type text/html;
    set $name kgc;
    echo $name;
    set $my_port $server_port;
    echo $my_port;
}

break指令

用于中断当前相同作用域(location)中的其他Nginx配置,与该指令处于同一作用域的Nginx配置中,位于它前面的配置生效,位于后面的 ngx_http_rewrite_module 模块中指令就不再执行,Nginx服务器在根据配置处理请求的过程中遇到该指令的时候,回到上一层作用域继续向下读取配置,该指令可以在server块和locationif块中使用

注意: 如果break指令在location块中后续指令还会继续执行,只是不执行 ngx_http_rewrite_module 模块的指令,其它指令还会执行

使用语法如下:

if ($slow) {
   limit_rate 10k;
   break;
}
location /main {
   root /data/nginx/html/pc;
   index index.html;
   default_type text/html;
    set $name kgc;
    echo $name;
   break;  #location块中break后面指令还会执行
    set $my_port $server_port;
    echo $my_port;
 }

rewrite指令

通过正则表达式的匹配来改变URI,可以同时存在一个或多个指令,按照顺序依次对URI进行匹配,rewrite主要是针对用户请求的URL或者是URI做具体处理

官方文档:

https://nginx.org/en/docs/http/ngx_http_rewrite_module.html#rewrite

rewrite可以配置在 server、location、if

语法格式 :


rewrite可以配置在 server、location、if
语法格式 :
rewrite regex               replacement        [flag];
        正则匹配原始访问url    替代你想让客户访问的              标志

rewrite将用户请求的URI基于regex所描述的模式进行检查,匹配到时将其替换为表达式指定的新的URI

注意:如果在同一级配置块中存在多个rewrite规则,那么会自下而下逐个检查;被某条件规则替换完成后,会重新一轮的替换检查,隐含有循环机制,但不超过10次;如果超过,提示500响应码,[flag]所表示的标志位用于控制此循环机制如果替换后的URL是以http://或https://开头,则替换结果会直接以重定向返回给客户端, 即永久重定向 301

正则表达式格式

. #匹配除换行符以外的任意字符
\w #匹配字母或数字或下划线或汉字
\s #匹配任意的空白符
\d #匹配数字     
\b #匹配单词的开始或结束
^ #匹配字付串的开始
$ #匹配字符串的结束
* #匹配重复零次或更多次
+ #匹配重复一次或更多次
? #匹配重复零次或一次
(n) #匹配重复n次
{n,} #匹配重复n次或更多次
{n,m} #匹配重复n到m次
*? #匹配重复任意次,但尽可能少重复
+? #匹配重复1次或更多次,但尽可能少重复
?? #匹配重复0次或1次,但尽可能少重复
{n,m}? #匹配重复n到m次,但尽可能少重复
{n,}? #匹配重复n次以上,但尽可能少重复
\W  #匹配任意不是字母,数字,下划线,汉字的字符
\S #匹配任意不是空白符的字符
\D #匹配任意非数字的字符
\B #匹配不是单词开头或结束的位置
[^x] #匹配除了x以外的任意字符
[^kgc] #匹配除了kgc 这几个字母以外的任意字符

rewrite flag 使用介绍

利用nginx的rewrite的指令,可以实现url的重新跳转,rewrtie有四种不同的flag,分别是redirect(临时重定向302)、permanent(永久重定向301)、break和last。其中前两种是跳转型的flag,后两种是代理型

  • 跳转型指由客户端浏览器重新对新地址进行请求
  • 代理型是在WEB服务器内部实现跳转

rewrite 格式

Syntax: rewrite regex replacement [flag]; #通过正则表达式处理用户请求并返回替换后的数据包。
Default: —
Context: server, location, if

flag 说明

redirect;302
#临时重定向,重写完成后以临时重定向方式直接返回重写后生成的新URL给客户端,由客户端重新发起请求;使用相对路径,或者http://或https://开头,状态码:302

permanent;301       www.bj.com     www.beijing.com
#重写完成后以永久重定向方式直接返回重写后生成的新URL给客户端,由客户端重新发起请求,状态码:301



break;       www.bj.com
#重写完成后,停止对当前URL在当前location中后续的其它重写操作,而后直接跳转至重写规则配置块之后的其它配置;结束循环,建议在location中使用
#适用于一个URL一次重写 





last;
#重写完成后,停止对当前URI在当前location中后续的其它重写操作,而后对新的URL启动新一轮重写检查,不建议在location中使用
#适用于一个URL多次重写,要注意避免出现超过十次以及URL重写后返回错误的给用户301

示例:


#访问  bj   跳转到  beijing  
location /bj {
   root /data/nginx/pc;   rewrite ^/bj/(.*)    /beijing/$1   permanent;

}






location / {
   root /data/nginx/html/pc;
   index index.html;
   rewrite / http://www.kgc.com permanent;
    #rewrite / http://www.kgc.com redirect;
 }
#重启Nginx并访问域名 http://www.kgc.org 进行测试

实战案例 http 转https

server {
 listen 443 ssl;
 listen 80;
 ssl_certificate /apps/nginx/certs/www.kgc.org.crt;
 ssl_certificate_key /apps/nginx/certs/www.kgc.org.key;
 ssl_session_cache shared:sslcache:20m;
 ssl_session_timeout 10m;
 server_name www.kgc.org;
 location / {    #针对全站跳转
   root /data/nginx/html/pc;
   index index.html;
    if ($scheme = http ){  #如果没有加条件判断,会导致死循环
   rewrite / https://$host redirect;
   }     http://www.kgc.com     https://www.kgc.com   
 }
 location /login {     #针对特定的URL进行跳转https 
 if ($scheme = http ){  #如果没有加条件判断,会导致死循环
   rewrite / https://$host/login redirect;
   }
    }
}

防盗链

防盗链基于客户端携带的referer实现,referer是记录打开一个页面之前记录是从哪个页面跳转过来的标记信息,如果别人只链接了自己网站图片或某个单独的资源,而不是打开了网站的整个页面,这就是盗链,referer就是之前的那个网站域名,正常的referer信息有以下几种:

none:#请求报文首部没有referer首部,比如用户直接在浏览器输入域名访问web网站,就没有referer信息。
blocked:#请求报文有referer首部,但无有效值,比如为空。
server_names:#referer首部中包含本主机名及即nginx 监听的server_name。
arbitrary_string:#自定义指定字符串,但可使用*作通配符。示例: *.kgc.org www.kgc.*
regular expression:#被指定的正则表达式模式匹配到的字符串,要使用~开头,例如:~.*\.kgc\.com

实现盗链

在二机器上:
yum install nginx
cd /usr/share/nginx/html
vim  test.html
<html>
<body>
<h1>this is ky26
<img src="http://192.168.91.100/a.jpg"/>
</body>
</html>

systemctl start nginx    

实现防盗链

location ~* \.(jpg|gif|swf)$ {            
         root  html;
         expires 1d;
         valid_referers none blocked *.kgc.com kgc.com;   
         if ( $invalid_referer ) {
           rewrite ^/ http://www.kgc.com/error.jpg;
           }
        }
        
        
        
~* \.(jpg|gif|swf)$:这段正则表达式表示匹配不区分大小写,以.jpg 或.gif 或.swf 结尾的文件
Valid_referers:设置信任的网站,可以正常使用图片。
None :浏览器中 referer 为空的情况,就是直接在浏览器访问图片。
Blocked :referer 不为空的情况 ,但是值被代理或防火墙删除了,这些值不以 http://或https://开头。
后面的网址或者域名:referer 中包含相关字符串的网址。
If 语句:如果链接的来源域名不在 valid_referers 所列出的列表中,$invalid_referer 为1,则执行后面的操作,即进行重写或返回 403 页面。
https://www.digitalocean.com/community/tools/nginx
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值