• Nginx安装及使用


    Nginx

    一.IO模型

    I/O在计算机中指Input/Output, IOPS (Input/Output Per Second)即每秒的输入输出量(或读写次数),是衡量磁盘性能的主要指标之一。

    Linux 的 I/O

    • 磁盘I/O 磁盘I/O是进程向内核发起系统调用,请求磁盘上的某个资源比如是html 文件或者图片,然后内核通过相应的驱动程序将目标文件加载到内核的内存空间,加载完成之后把数据从内核内存再复制给进程内存,如果是比较大的数据也需要等待时间

    • 网络I/O : 一切皆文件,本质为对socket文件的读写 网络通信就是网络协议栈到用户空间进程的IO就是网络IO

    1.客户端发起请求 先发送到网卡   
    2.网卡收到的报文复制到内核空间
    3.内核空间再复制到用户空间的应用程序空间
    4.nginx 分析得到一个磁盘页面文件
    5.再将需求反馈给内核空间,应为应用程序没有权限从磁盘上直接读取文件,需要依靠内核
    6.内核去磁盘上找到所需要的文件,加载到内核空间
    7.加载后再复制到用户空间
    8.用户空间构建响应报文,交给内核空间,内核空间再复制给网卡,返回给用户
    整个过程会来回切换 用户空间,内核空间  那么我们可以再次基础上做优化处理
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    当用户发起 http 请求需要请求一个index.htm] 网页文件
    客户端请求与服务器端 建立连接,建立连接后,会发送请求报文
    服务端的网卡收到请求报文,会将该报文复制到内核空间,内核空间分析报文后交给对应的程序
    nginx分析该报文,将报文和自己的配置文件一一比对,按照配置文件完成请求,分析后发现客户端需要index.html
    由于程序的权限问题,没有资格直接调用磁盘上的文件,程序会再次将这个请求转发给内核
    内核得到请求去磁盘上找文件,找到文件后复制给程序
    程序会构建响应报文,构建好之后交给内核空间,
    内核空间再交给网卡发送给客户端
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    1.I/O模型相关概念

    同步/异步(消息反馈机制):关注的是消息通信机制,即调用者在等待一件事情的处理结果时,被调用者是否提供完成状态的通知。

    • 同步:synchronous,被调用者并不提供事件的处理结果相关的通知消息,需要调用者主动询问事情是否处理完成。
    • 异步:asynchronous,被调用者通过状态、通知或回调机制主动通知调用者被调用者的运行状态。

    阻塞/非阻塞:关注调用者在等待结果返回之前所处的状态

    • 阻塞:blocking,指IO操作需要彻底完成后才返回到用户空间,调用结果返回之前,调用者被挂起,干不了别的事情。
    • 非阻塞:nonblocking,指IO操作被调用后立即返回给用户一个状态值,而无需等到IO操作彻底完成,在最终的调用结果返回之前,调用者不会被挂起,可以去做别的事情。

    2.网络I/O模型

    阻塞型I/O模型

    阻塞IO模型是最简单的I/O模型,用户线程在内核进行IO操作时被阻塞用户线程通过系统调用read发起I/O读操作,由用户空间转到内核空间。内核等到数据包到达后,然后将接收的数据拷贝到用户空间,完成read操作用户需要等待read将数据读取到buffer后,才继续处理接收的数据。整个I/O请求的过程中,用户线程是被阻塞的,这导致用户在发起IO请求时,不能做任何事情,对CPU的资源利用率不够

    • 优点:程序简单,在阻塞等待数据期间进程/线程挂起,基本不会占用 CPU 资源
    • 缺点:每个连接需要独立的进程/线程单独处理,当并发请求量大时为了维护程序,内存、线程切换开销较大,apache 的preforck使用的是这种模式。
    同步阻塞:程序向内核发送I/O请求后一直等待内核响应,如果内核处理请求的IO操作不能立即返回,则进程将一直等待并不再接受新的请求,并由进程轮训查看I/O是否完成,完成后进程将I/O结果返回给Client,在IO没有返回期间进程不能接受其他客户的请求,而且是有进程自己去查看I/O是否完成,这种方式简单,但是比较慢,用的比较少。
    
    • 1
    非阻塞型I/O模型

    用户线程发起IO请求时立即返回。但并未读取到任何数据,用户线程需要不断地发起IO请求,直到数据到达后,才真正读取到数据,继续执行。即 “轮询”机制存在两个问题:如果有大量文件描述符都要等,那么就得一个一个的read。这会带来大量的Context Switch(read是系统调用,每调用一次就得在用户态和核心态切换一次)。轮询的时间不好把握。这里是要猜多久之后数据才能到。等待时间设的太长,程序响应延迟就过大;设的太短,就会造成过于频繁的重试,干耗CPU而已,是比较浪费CPU的方式,一般很少直接使用这种模型,而是在其他IO模型中使用非阻塞IO这一特性。

    非阻塞:程序向内核发送请I/O求后一直等待内核响应,如果内核处理请求的IO操作不能立即返回IO结果,进程将不再等待,而且继续处理其他请求,但是仍然需要进程隔一段时间就要查看内核I/O是否完成。
    
    • 1
    多路复用 I/O 型

    I/O multiplexing 主要包括:select,poll,epoll三种系统调用,select/poll/epoll的好处就在于单个process就可以同时处理多个网络连接的IO。它的基本原理就是select/poll/epoll这个function会不断的轮询所负责的所有socket,当某个socket有数据到达了,就通知用户进程。当用户进程调用了select,那么整个进程会被block,而同时,kernel会“监视”所有select负责的socket,当任何一个socket中的数据准备好了,select就会返回。这个时候用户进程再调用read操作,将数据从kernel拷贝到用户进程。Apache prefork是此模式的select,work是poll模式。

    信号驱动式 I/O模型

    信号驱动I/O的意思就是我们现在不用傻等着了,也不用去轮询。而是让内核在数据就绪时,发送信号通知我们。

    调用的步骤是,通过系统调用 sigaction ,并注册一个信号处理的回调函数,该调用会立即返回,然后主程序可以继续向下执行,当有I/O操作准备就绪,即内核数据就绪时,内核会为该进程产生一个SIGIO 信号,并回调注册的信号回调函数,这样就可以在信号回调函数中系统调用 recvfrom 获取数据,将用户进程所需要的数据从内核空间拷贝到用户空间

    此模型的优势在于等待数据报到达期间进程不被阻塞。用户主程序可以继续执行,只要等待来自信号处理函数的通知。

    在信号驱动式 I/O 模型中,应用程序使用套接口进行信号驱动 I/O,并安装一个信号处理函数,进程继续运行并不阻塞

    当数据准备好时,进程会收到一个 SIGIO 信号,可以在信号处理函数中调用 I/O 操作函数处理数据。

    • 优点:线程并没有在等待数据时被阻塞,内核直接返回调用接收信号,不影响进程继续处理其他请求因此可以提高资源的利用率
    • 缺点:信号 I/O 在大量 IO 操作时可能会因为信号队列溢出导致没法通知
    异步I/O模型

    异步I/O 与 信号驱动I/O最大区别在于,信号驱动是内核通知我们何时开始一个I/O操作,而异步I/O是由内核通知我们I/O操作何时完成

    总结

    这五种 I/O 模型中,越往后,阻塞越少,理论上效率也是最优前四种属于同步 I/O,因为其中真正的I/O 操作(recvfrom)将阻塞进程/线程,只有异步 I/O 模型才与 POSIX 定义的异步 I/O 相匹配

    Nginx支持在多种不同的操作系统实现不同的事件驱动模型,但是其在不同的操作系统甚至是不同的系统版本上面的实现方式不尽相同,主要有以下实现方式:

    1、select:
    select库是在linux和windows平台都基本支持的 事件驱动模型库,并且在接口的定义也基本相同,只是部
    分参数的含义略有差异,最大并发限制1024,是最早期的事件驱动模型。
    2、poll:
    在Linux 的基本驱动模型,windows不支持此驱动模型,是select的升级版,取消了最大的并发限制,在编
    译nginx的时候可以使用--with-poll_module和--without-poll_module这两个指定是否编译select
    库。
    3、epoll:
    epoll是库是Nginx服务器支持的最高性能的事件驱动库之一,是公认的非常优秀的事件驱动模型,它和
    select和poll有很大的区别,epoll是poll的升级版,但是与poll有很大的区别.
    epoll的处理方式是创建一个待处理的事件列表,然后把这个列表发给内核,返回的时候在去轮训检查这个
    表,以判断事件是否发生,epoll支持一个进程打开的最大事件描述符的上限是系统可以打开的文件的最大
    数,同时epoll库的I/O效率不随描述符数目增加而线性下降,因为它只会对内核上报的“活跃”的描述符进行
    操作。
    4、rtsig:
    不是一个常用事件驱动,最大队列1024,不是很常用
    5、kqueue:
    用于支持BSD系列平台的高校事件驱动模型,主要用在FreeBSD 4.1及以上版本、OpenBSD 2.0级以上版
    本,NetBSD级以上版本及Mac OS X 平台上,该模型也是poll库的变种,因此和epoll没有本质上的区别,
    都是通过避免轮训操作提供效率。
    6、/dev/poll:
    用于支持unix衍生平台的高效事件驱动模型,主要在Solaris 平台、HP/UX,该模型是sun公司在开发
    Solaris系列平台的时候提出的用于完成事件驱动机制的方案,它使用了虚拟的/dev/poll设备,开发人员
    将要见识的文件描述符加入这个设备,然后通过ioctl()调用来获取事件通知,因此运行在以上系列平台的时
    候请使用/dev/poll事件驱动机制。
    7、eventport:
    该方案也是sun公司在开发Solaris的时候提出的事件驱动库,只是Solaris 10以上的版本,该驱动库看防
    止内核崩溃等情况的发生。
    8、Iocp:
     Windows系统上的实现方式,对应第5种(异步I/O)模型。
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    Select:
    POSIX所规定,目前几乎在所有的平台上支持,其良好跨平台支持也是它的一个优点,本质上是通过设置或者
    检查存放fd标志位的数据结构来进行下一步处理
    缺点
    单个进程能够监视的文件描述符的数量存在最大限制,在Linux上一般为1024,可以通过修改宏定义
    FD_SETSIZE,再重新编译内核实现,但是这样也会造成效率的降低
    单个进程可监视的fd数量被限制,默认是1024,修改此值需要重新编译内核
    对socket是线性扫描,即采用轮询的方法,效率较低
    select 采取了内存拷贝方法来实现内核将 FD 消息通知给用户空间,这样一个用来存放大量fd的数据结
    构,这样会使得用户空间和内核空间在传递该结构时复制开销大
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    poll:
    本质上和select没有区别,它将用户传入的数组拷贝到内核空间,然后查询每个fd对应的设备状态
    其没有最大连接数的限制,原因是它是基于链表来存储的
    大量的fd的数组被整体复制于用户态和内核地址空间之间,而不管这样的复制是不是有意义
    poll特点是“水平触发”,如果报告了fd后,没有被处理,那么下次poll时会再次报告该fd 
    select是边缘触发即只通知一次
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    epoll:
    在Linux 2.6内核中提出的select和poll的增强版本
    支持水平触发LT和边缘触发ET,最大的特点在于边缘触发,它只告诉进程哪些fd刚刚变为就需态,并且只会
    通知一次
    使用“事件”的就绪通知方式,通过epoll_ctl注册fd,一旦该fd就绪,内核就会采用类似callback的回调
    机制来激活该fd,epoll_wait便可以收到通知
    优点:
    没有最大并发连接的限制:能打开的FD的上限远大于1024(1G的内存能监听约10万个端口),具体查
    看/proc/sys/fs/file-max,此值和系统内存大小相关
    效率提升:非轮询的方式,不会随着FD数目的增加而效率下降;只有活跃可用的FD才会调用callback函数,
    即epoll最大的优点就在于它只管理“活跃”的连接,而跟连接总数无关
    内存拷贝,利用mmap(Memory Mapping)加速与内核空间的消息传递;即epoll使用mmap减少复制开销
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    二.Nginx概述

    Nginx 功能介绍

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

    基础特性

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

    Web 服务相关的功能

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

    Nginx 进程结构

    web请求处理机制

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

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

    主进程(master process)的功能:

    对外接口:接收外部的操作(信号)
    对内转发:根据外部的操作的不同,通过信号管理 Worker
    监控:监控 worker 进程的运行状态,worker 进程异常终止后,自动重启 worker 进程
    读取Nginx 配置文件并验证其有效性和正确性
    建立、绑定和关闭socket连接
    按照配置生成、管理和结束工作进程
    接受外界指令,比如重启、升级及退出服务器等指令
    不中断服务,实现平滑升级,重启服务并应用新的配置
    开启日志文件,获取文件描述符
    不中断服务,实现平滑升级,升级失败进行回滚处理
    编译和处理perl脚本
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    工作进程(worker process)的功能:

    所有 Worker 进程都是平等的
    实际处理:网络请求,由 Worker 进程处理
    Worker进程数量:一般设置为核心数,充分利用CPU资源,同时避免进程数量过多,导致进程竞争CPU资源,
    增加上下文切换的损耗
    接受处理客户的请求
    将请求依次送入各个功能模块进行处理
    I/O调用,获取响应数据
    与后端服务器通信,接收后端服务器的处理结果
    缓存数据,访问缓存索引,查询和调用缓存数据
    发送请求结果,响应客户的请求
    接收主程序指令,比如重启、升级和退出等
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    三.Nginx模块

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

    四.安装及使用Nginx

    1.编译安装Nginx

    源码包内的文件:

    contrib:vim 格式文件,修改nginx配置文件的格式,高亮 cp -r /opt/nginx-1.18.0/contrib/vim/* /usr/share/vim/vimfiles/

    conf:配置文件

    man:man帮助 man man/nginx.8 不加路径看不了 nginx.8 文件

    src:源码包 .c .h 结尾的文件

    yum -y install gcc pcre-devel openssl-devel zlib-devel openssl  openssl-devel
    //安装依赖包   
    useradd -M -s /sbin/nologin nginx
    //新建nginx用户便于管理
    [root@localhost opt]#wget http://nginx.org/download/nginx-1.18.0.tar.gz
    //在opt下下载源码包
    [root@localhost opt]#mkdir /apps/nginx -p
    [root@localhost opt]#tar xf nginx-1.18.0.tar.gz 
    //解压
    [root@localhost opt]#cd nginx-1.18.0/
    [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
    [root@localhost nginx-1.18.0]#make -j2 && 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 8月  23 17:03 conf
    drwxr-xr-x. 2 nginx nginx   40 8月  23 17:03 html
    drwxr-xr-x. 2 nginx nginx    6 8月  23 17:03 logs
    drwxr-xr-x. 2 nginx nginx   19 8月  23 17:03 sbin
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    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二进制启动脚本,可以接受不同的参数以实现不同的功能。
    [root@localhost nginx-1.18.0]#ln -s /apps/nginx/sbin/nginx /usr/sbin/
    //创建软连接方便操作
    
    
    • 1
    • 2
    • 3
    //创建Nginx 自启动文件
    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/logs/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]#systemctl daemon-reload
    //重新加载文件
    
    如果需要修改pid文件可以执行以下操作
    [root@localhost nginx-1.18.0]#mkdir /apps/nginx/run/
    [root@localhost nginx-1.18.0]#vim /apps/nginx/conf/nginx.conf
    
    #pid   /apps/nginx/run/nginx.pid;   //修改路径
    
    [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
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    2.yum安装

    yum install -y epel-release
    #安装epel源
    yum install nginx -y
    
    • 1
    • 2
    • 3

    安装最新版本可去官网查询方法(下面有不同系统的不同方法)

    https://nginx.org/en/linux_packages.html
    
    • 1

    3.命令及信号使用

    [root@node2 ~]#nginx -h
      -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: /etc/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
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    nginx -t   检查语法格式
    
    
    nginx -g   指定配置 不以配置文件中的为准
    例如:
    nginx -g 'user zhangsan;'   已张三身份运行,默认是以nginx身份
    nginx -g 'daemon off;'    前台运行命令
    
    nginx -s   stop   //立即关闭nginx
    nginx -s   quit   //优雅退出   不影响业务的状态下退出
    nginx -s   reload //重新加载  
    可以使用man手册来查看详细的信号 如果没安装,去源码包里找到man文件
    man   路径/nginx.8  不加路径打不开man帮助
    
    nginx -h   中可以看到的信号较少
    
    stop      	SIGTERM        直接停止
    quit       	SIGQUIT        任务结束退出:有人在访问不会结束进程
    reopen   	SIGUSR1        分割日志
    reload   	SIGHUP         重新加载配置文件
    
    nginx -V    //显示编译详细情况 模块等信息
    
    nginx -v    //显示版本
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    4.USR1分割日志

    [root@localhost logs]#cd /apps/nginx/logs/
    //切换到存放日志的文件夹
    [root@localhost logs]#mv access.log access.log.bak
    [root@localhost logs]#touch access.log
    //此时日志不会写入到新文件,而是写到.bak下
    需要给master 进程发送  USR1信号
    
    [root@localhost logs]#ps aux |grep -v grep|grep nginx
    root       7142  0.0  0.0  46156  1160 ?        Ss   17:25   0:00 nginx: master process /apps/nginx/sbin/nginx -c /apps/nginx/conf/nginx.conf
    nginx      7143  0.0  0.1  48688  2252 ?        S    17:25   0:00 nginx: worker process
    
    [root@localhost logs]#nginx -s reopen 
    或者
    [root@localhost logs]#kill -s  USR1 7142
    
    //这是就会把日志写到新的文件里
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    5.升级Nginx

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

    五.配置详细解释

    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 {负载均衡
     ...
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40

    1.全局配置

    nginx 有多种模块

    • 核心模块:是 Nginx 服务器正常运行必不可少的模块,提供错误日志记录 、配置文件解析 、事件驱动机制 、进程管理等核心功能
    • 标准HTTP模块:提供 HTTP 协议解析相关的功能,比如: 端口配置 、 网页编码设置 、 HTTP响应头设置 等等
    • 可选HTTP模块:主要用于扩展标准的 HTTP 功能,让 Nginx 能处理一些特殊的服务,比如:Flash 多媒体传输 、解析 GeoIP 请求、 网络传输压缩 、 安全协议 SSL 支持等
    • 邮件服务模块:主要用于支持 Nginx 的 邮件服务 ,包括对 POP3 协议、 IMAP 协议和 SMTP协议的支持
    • Stream服务模块: 实现反向代理功能,包括TCP协议代理
    • 第三方模块:是为了扩展 Nginx 服务器应用,完成开发者自定义功能,比如: Json 支持、 Lua 支持等
    修改启动的进程数
    worker_processes auto;
    在配置文件中把数量改为自动auto,会根据实际的cpu数量而修改进程数
    [root@localhost logs]#ps axo pid,cmd,psr,ni|grep nginx
      7142 nginx: master process /apps   2   0
     11557 nginx: worker process         7   0
     11558 nginx: worker process         8   0
     11559 nginx: worker process        14   0
     11560 nginx: worker process         6   0
     11561 nginx: worker process        10   0
     11562 nginx: worker process        15   0
     11563 nginx: worker process         3   0
     11564 nginx: worker process         9   0
     11565 nginx: worker process         4   0
     11566 nginx: worker process        12   0
     11567 nginx: worker process        11   0
     11568 nginx: worker process         5   0
     11569 nginx: worker process         9   0
     11570 nginx: worker process        10   0
     11571 nginx: worker process         6   0
     11572 nginx: worker process        13   0
     11574 grep --color=auto nginx       2   0
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    cpu和work进程绑定

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

    CPU序号:
    CPU MASK: 00000001:0号CPU
              00000010:1号CPU
              ................
      		  10000000:7号CPU
    worker_cpu_affinity 00000001 00000010 00000100 00001000;第0号---第3号CPU   
    //序号绑定cpu    亲缘性
    worker_cpu_affinity 00000101 00001010;
    //同一个work  可以绑定两个cpu可以这么写 但是不建议,本来就是 不希望飘动,这样也是飘动
    
    worker_cpu_affinity 0000000000000010;
      		  
    [root@localhost logs]#ps axo pid,cmd,psr,ni|grep -v grep |grep nginx|sort -n
      7142 nginx: master process /apps   3   0
     11757 nginx: worker process         1   0
     11758 nginx: worker process         1   0
     11759 nginx: worker process         1   0
     11760 nginx: worker process         1   0
     11761 nginx: worker process         1   0
     11762 nginx: worker process         1   0
     11763 nginx: worker process         1   0
     11764 nginx: worker process         1   0
     11765 nginx: worker process         1   0
     11766 nginx: worker process         1   0
     11767 nginx: worker process         1   0
     11768 nginx: worker process         1   0
     11769 nginx: worker process         1   0
     11770 nginx: worker process         1   0
     11771 nginx: worker process         1   0
     11772 nginx: worker process         1   0
     //全部绑定在一号cpu上,实际情况要根据cpu数量来写,否则写少了一样会飘动
     
    验证cpu乱跑可以刷新网页即可
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    nginx进程的优先级(work进程的优先级)
    nice的优先级是  -20 到 19
    
    worker_priority 0; 
    #工作进程优先级,-20~20(19)
    
    [root@localhost logs]#ps axo pid,cmd,psr,ni|grep nginx|sort -n
      7142 nginx: master process /apps   3   0
     11757 nginx: worker process         1   0
     11758 nginx: worker process         1   0
     11759 nginx: worker process         1   0
     11760 nginx: worker process         1   0
     11761 nginx: worker process         1   0
     11762 nginx: worker process         1   0
     11763 nginx: worker process         1   0
    .........
    
    将worker_priority -20;写入配置文件
    
    [root@localhost logs]#ps axo pid,cmd,psr,ni|grep nginx|sort -n
      7142 nginx: master process /apps   3   0
     11845 nginx: worker process         1 -20
     11846 nginx: worker process         1 -20
     11847 nginx: worker process         1 -20
     11848 nginx: worker process         1 -20
     11849 nginx: worker process         1 -20
     11850 nginx: worker process         1 -20
    ..........
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    修改PID 路径
    pid /run/nginx.pid;
    
    
    pid  进程号文件位置可以自定义省略
    
    • 1
    • 2
    • 3
    • 4
    调试work进程打开的文件的个数
    worker_priority -20;
    worker_rlimit_nofile 65536;
    //将其写入配置文件表示可以打开65536个文件
    所有worker进程能打开的文件数量上限,包括:Nginx的所有连接(例如与代理服务器的连接等),而不仅仅是与客户端的连接,另一个考虑因素是实际的并发连接数不能超过系统级别的最大打开文件数的限制.最好与ulimit -n 或者limits.conf的值保持一致
    只要机器性能够多加几个也没问题
    
    worker_connections  数量;
    调整每个worker进程可打开文件数量
    
    [root@localhost logs]#cd /apps/nginx/html
    
    dd if=/dev/zero  of=big.img  bs=100M count=1
    //做测试用文件
    
    客户端
    [root@localhost ~]#yum install httpd-tools -y
    //安装压力测试的工具
    [root@localhost ~]ab -c 1000 -n 10000 http://192.168.91.100/big.img
    
    在服务端
    [root@localhost html]#ls /proc/7142/fd
    0  10  12  14  16  18  2   21  23  25  27  29  31  33  35  37  39  5  8
    1  11  13  15  17  19  20  22  24  26  28  30  32  34  36  38  4   6  9
    .......................
    //无法响应客户端的需求
    
    这时可以想到系统的默认项
    
    [root@localhost html]#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) 7168
    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) 7168
    virtual memory          (kbytes, -v) unlimited
    file locks                      (-x) unlimited
    
    [root@localhost html]#ulimit -n 60000
    //只是临时修改,可以看看之前系统安全相关知识,修改pam认证文件
    
    注意两端都要修改
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    服务是否以后台方式运行
    一般服务都是后台运行,前台容器中会用到
    
    worker_processes auto;
    worker_cpu_affinity 00000101 00000010;
    daemon off;
    //加入此项
    
    
    [root@localhost ~]#systemctl start nginx
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    只有 master进程没有 work进程
    master_process off|on;
    //是否开启Nginx的master-worker工作模式,仅用于开发调试场景,默认为on
    
    • 1
    • 2

    2.event事件

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

    3.http设置

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

    http {
     ...
     ...  各server的公共配置
     server {    每个server用于定义一个虚拟主机,第一个server为默认虚拟服务器
     ...
     }
     server {     
     ...
     server_name   虚拟主机名
     root     主目录
     alias    路径别名
     location [OPERATOR] URL {     指定URL的特性
     ...
     if CONDITION {
     ...
     }
     }
     }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    http 协议配置说明

    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,可以以空格隔开写多个并支持正则表达式,如:*.kgc.com www.kgc.* ~^www\d+\.kgc\.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;
        #   }
        #}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    server下的root

    root指定了主页文件的位置

    root路径格式 指定文件的路径    url  
    指明软件根目录
    
    • 1
    • 2
    关闭版本或修改版本
    Syntax:	server_tokens on | off | build | string;
    [root@localhost logs]#vim /apps/nginx/conf/nginx.conf
    http {
        server_tokens  off;
        .........
        }
    [root@localhost logs]#nginx -s reload
    //重新加载配置文件
    
    另一台主机
    [root@localhost ~]#curl -I 192.168.82.100
    HTTP/1.1 200 OK
    Server: nginx
    Date: Wed, 23 Aug 2023 10:20:02 GMT
    Content-Type: text/html
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    去修改源码,在安装包里, 再重新编译  #号不要去掉
    
    [root@localhost logs]#vim  /opt/nginx-1.18.0/src/core/nginx.h
    13行 #define NGINX_VERSION      "9999"
    14行 #define NGINX_VER          "http/" NGINX_VERSION
    
    [root@localhost logs]#vim /opt/nginx-1.18.0/src/http/ngx_http_header_filter_module.c 
    49行 static u_char ngx_http_server_string[] = "Server: xxxxx" CRLF;
    
    
    重新编译安装
    ./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
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    server块构建虚拟主机

    建立独立配置文件,根据端口,ip,域名建立虚拟主机

    从而访问不同页面

    要在主配置文件中添加
    修改配置文件 要放在  http 模块里
    include /相应的子配置文件路径;
    mkdir建立相应的子配置文件
    
    [root@localhost conf.d]#vim hh.conf
    server {
       listen 80;
       server_name localhost;
       root /apps/nginx/html/hh/;
    }
    //表示监听80端口,省略了ip地址默认所有ip地址的80端口
    
    或者使用location模块
    
    server{
            listen   192.168.82.100:80;
            server_name www.hh.com;
         location / {
            root  /apps/nginx/html/hh;
        }
    }
    
    
    同样的方式构建另一个配置
    server{
         listen 192.168.82.100:80;
         server_name www.aa.com;
         location / {
         root /apps/nginx/html/aa;
         }
    }
    
    
    [root@localhost html]#mkdir aa hh
    [root@localhost html]#ls
    50x.html  aa  big.img  hh  index.html
    
    
    [root@localhost hh]#echo hh > /apps/nginx/html/hh/index.html
    同样的再建立aa
    
    然后重新加载配置文件
    
    另一台主机
    [root@localhost html]#vim /etc/hosts
    //添加域名
    [root@localhost html]#curl www.hh.com
    hh
    [root@localhost html]#curl www.aa.com
    aa
    
    
    基于端口或者ip与apache相同
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    别名alias
    server {
       listen 80;
       server_name www.hh.com;
       location /wwww {
            root /apps/nginx/html/hh/;
            //相当于追加  将 文件夹hh追到/data/nginx/html/hh/wwww
            }
       
       location /ggggg{
            alias /apps/nginx/mila/;
            //相当于替换 你访问 ggggg 就是访问/apps/nginx/mila
            }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    location

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

    官方帮助:

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

    location [ = | ~ | ~* | ^~ ] uri { ... }
    
    =              	//用于标准uri前,需要请求字串与uri精确匹配,大小敏感,如果匹配成功就停止向下匹配并立即处理请求
    ^~            	//用于标准uri前,表示包含正则表达式,并且匹配以指定的正则表达式开头,对URI的最左边部分做匹配检查,不区分字符大小写
    ~              	//用于标准uri前,表示包含正则表达式,并且区分大小写
    ~*            	//用于标准uri前,表示包含正则表达式,并且不区分大写
    不带符号   	  	  //匹配起始于此uri的所有的uri
     \              //用于标准uri前,表示包含正则表达式并且转义字符。可以将 . * ?等转义为普通符号
     
    //匹配优先级从高到低:
    =, ^~, ~/~*, 不带符号
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    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.
    
    官方帮助提供的案例
    访问路径是    /      A                   
    访问路径是    /index.html   B
    访问路径是    /documents/document.html   C
    访问路径是    /images/1.gif   D
    访问路径是    /documents/1.jpg   E
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    不区分大小写
    location ~* /A.?\.jpg {
      //匹配以A后面一个或没有字符,已.jpg结尾的图片
       root /apps/nginx/html/image;
     }
     
     虽然 不区分大小写  但是系统的文件系统区分大小写,所以应用此location,应该建立相同名字的大写文件
     
     只要是图片就去 images中找
    server{
    location ~* \.(gif|jpg|jpeg|bmp|png|tiff|tif|ico|wmf|js|css)$ {
            root /apps/nginx/html/images/;
     }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    匹配优先级验证
    此处的优先级有小问题
    server{
            listen 80;
            server_name  www.hh.com;
         location = / {
            root   /apps/nginx/html/hh;
            }
            location / {
            root   /apps/nginx/html/aa;
            }
    }
    
    实际访问到/apps/nginx/html/aa下的index
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    location = /1.html{
       root /apps/nginx/static1;
       }
     location /1.html {
       root /apps/nginx/static2;
      }
     location ~* \.html$ {
       root /apps/nginx/static3;
      }
     
     访问www.hh.com/1.html
     删除第一个location继续验证www.hh.com/1.html
     删除第二个location继续验证www.hh.com/1.html
     分别显示ww rr ee 对应了三个static里面的1.html
     可知location优先级:(location =) > (location ^~ 路径) > (location ~,~* 正则顺序) > 
    (location 完整路径) > (location 部分起始路径) > (/)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    #直接匹配网站根会加速Nginx访问处理
    location = /index.html {
       ......;
    }
    location / {
       ......;
    }
    #静态资源配置方法1
    location ^~ /static/ {
       ......;
    }
    #静态资源配置方法2,应用较多
    location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ {
       ......;
    }
    #多应用配置
    location ~* /app1 {
         ......;
    }
    location ~* /app2 {
         ......;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    access 模块 四层控制

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

    [root@localhost nginx-1.18.0]#./configure --help |grep access
      --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
    
    //去源码包中过滤access模块
    
    location / {
        deny  192.168.1.1;
        allow 192.168.1.0/24;
        allow 10.1.1.0/16;
        allow 2001:0db8::/32;
        deny  all;
    }
    
    //此处相当于白名单,支持ipv6
    
    匹配了之后就不往下匹配了
    所以范围小的往上
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    验证模块
     location /admin{
            root /data/nginx/html/pc;
            auth_basic    "admin site";
            #提示信息,不是所有浏览器都有用
            auth_basic_user_file /apps/nginx/conf.d/.httpuser;
            #密码文件存放位置
     }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    密码文件需要软件生成

    由httpd-tools包提供

    第一次生成文件
    htpasswd -c  文件路径 姓名        	 交互式生成密码
    htpasswd -bc 文件路径 姓名 密码   		直接将密码跟在后面 
    
    -c  代表新建用户名和密码对应的文件
    -b  将密码跟在用户名后
    
    非第一次
    htpasswd     文件路径 姓名        	 交互式生成密码
    htpasswd -b  文件路径 姓名 密码   		直接将密码跟在后面
    
    第一次
    [root@localhost nginx-1.18.0]#htpasswd -bc /apps/nginx/conf.d/.httpuser yyds 123456
    Adding password for user yyds
    [root@localhost nginx-1.18.0]#cat /apps/nginx/conf.d/.httpuser
    yyds:$apr1$4vfUuodD$pAh1Rj/hiOSxDIQifAOv80
    
    非第一次
    [root@localhost nginx-1.18.0]#htpasswd /apps/nginx/conf.d/.httpuser yyds
    New password: 
    Re-type new password: 
    Updating password for user yyds
    //修改密码
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    自定义 错误页面

    我们 可以改变 默认的错误页面,同时也可以用指定的响应状态码进行响应, 可用位置:http, server, location, if in location

    格式:

    error_page code ... [=[response]] uri;
    页面错误代码  
    error_page    固定写法
    code          响应码
    =             可以将响应码转换
    uri           访问连接
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    server{
        listen 192.168.82.100:80;
        server_name www.hh.com;
        root /apps/nginx/html/hh;
        error_page 404 /40x.html;
        //当出现404 错误  就去  root /apps/nginx/html/error/ 这个文件夹找40x.html  这个文件
        location = /40x.html {
        root /apps/nginx/html/error/;
    }
    }
    
    [root@www conf.d]#mkdir /apps/nginx/html/error/
    [root@www conf.d]#touch /apps/nginx/html/error/40x.html
    //新建配置文件中的路径及页面
    
    自定义 错误码
    
    可以将错误码指定为其他状态码
    error_page 404 =302 /40x.html;
    
    //404跳转主页面
    server {
       listen 80;
       server_name www.hh.com;
       root /apps/nginx/html/;
       error_page 404 =302 /index.html;
       //把错误码 404 指定成302  并跳到主页面:/index.html
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    日志位置存放
    Syntax: error_log file [level];
    error_log    /apps/nginx/logs/kgc_error.log;
    固定格式      文件路径                         级别(info  debug等  可以忽略不写)
    
    
    
    
    server{
        listen 192.168.82.100:80;
        server_name www.hh.com;
        root /apps/nginx/html/hh;
        error_page 404  /40x.html;
        access_log /apps/nginx/logs/hh_access.log; 
        error_log /apps/nginx/logs/hh_error.log;
        //定义错误日志文件
        location = /40x.html {
        root /apps/nginx/html/error/;
    }
    }
    [root@www conf.d]#cat /apps/nginx/logs/hh_access.log 
    192.168.82.101 - - [25/Aug/2023:16:12:07 +0800] "GET /xxxxx HTTP/1.1" 404 6 "-" "curl/7.29.0"
    
    [root@www conf.d]#cat /apps/nginx/logs/hh_error.log 
    2023/08/25 16:12:07 [error] 3320#0: *3 open() "/apps/nginx/html/hh/xxxxx" failed (2: No such file or directory), client: 192.168.82.101, server: www.hh.com, request: "GET /xxxxx HTTP/1.1", host: "www.hh.com"
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    检测文件是否存在

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

    Syntax: try_files file ... uri;
    try_files file ... =code;
    Default: —
    Context: server, location
    
    • 1
    • 2
    • 3
    • 4
    server{
        listen 192.168.82.100:80;
        server_name www.hh.com;
        root /apps/nginx/html/hh;
        access_log /apps/nginx/logs/hh_access.log;
        error_log /apps/nginx/logs/hh_error.log;
        try_files $uri $uri.html $uri/index.html /about/default.html;
    
    }
    我的访问是路径下的xxx文件,那按照设置,先会去找XXX,没有XXX会在后面加上XXX.html,再没有会在路径后补上XXX/index.html
    最后没有会有一个必须存在的页面
    
    [root@www ~]#mkdir -p /apps/nginx/html/hh/about/
    [root@www ~]#echo "default page" >> /apps/nginx/html/hh/about/default.html
    
    
    另一台主机
    [root@localhost ~]#curl www.hh.com/xxx
    default page
    
    
    还可以自定义返回码
    server{
            listen 80;
            server_name  www.hh.com;
            root /data/nginx/pc;
            location  / {
            root      /apps/nginx/html/hh;
            try_files $uri  $uri.html $uri/index.html =489;
            }
            error_page 489 /40x.html;
            location = /40x.html {
            root    /data/nginx/error/;
            }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    长连接

    http 基于 tcp 协议 先要 三次握手然后 再传输数据

    一次三次握手 下载多个资源

    keepalive_timeout timeout [header_timeout];  
    //设定保持连接超时时长,0表示禁止长连接,默认为75s,通常配置在http字段作为站点全局配置
    keepalive_requests number;  
    //在一次长连接上所允许请求的资源的最大数量,默认为100次,建议适当调大,比如:500
    可以加在全局或者 server 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    keepalive_requests 3;
    //最大下载三个资源断开连接
    keepalive_timeout 60 65;   #只能有一个空格 
    //开启长连接后,返回客户端的会话保持时间为60s,单次长连接累计请求达到指定次数请求或65秒就会被断开,后面的60为发送给客户端应答报文头部中显示的超时时间设置为60s:如不设置客户端将不显示超时时间。
    Keep-Alive:timeout=60  #浏览器收到的服务器返回的报文
    //如果设置为0表示关闭会话保持功能,将如下显示:
    Connection:close  #浏览器收到的服务器返回的报文
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    keepalive_disable none | browser ...;  
    //对哪种浏览器禁用长连接
    
    • 1
    • 2
    作为下载服务器配置

    ngx_http_autoindex_module 模块处理以斜杠字符 “/” 结尾的请求,并生成目录列表,可以做为下载服务

    autoindex on | off;
    //自动文件索引功能,默为off
    autoindex_exact_size on | off;  
    //计算文件确切大小(单位bytes),off 显示大概大小(单位K、M),默认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
    //变量提供 限制   变量优先级高
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    location /download {
           autoindex on;
           //开启下载服务器
           autoindex_exact_size on;
           //开启确切大小不建议开启
           autoindex_localtime on;
           //使用当地时间
           limit_rate 1024k;
           //所有人限速1024k,默认单位是字节数
           set $limit_rate 2M;
           //谁先生效
           alias /opt/download;
      }
    
    
    注意创建的文件夹下可以没有index.html,可将其他资源挂载在此文件夹供下载
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    用户上传资料

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

    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
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    其他设置
    directio size | off;
    //操作完全和aio相反,aio是读取文件而directio是写文件到磁盘,启用直接I/O,默认为关闭,当文件大于等于给定大小时,例如:directio 4m;同步(直接)写磁盘,而非写缓存。
    
    • 1
    • 2
    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
    limit_except method ... { ... },仅用于location
    //限制客户端使用除了指定的请求方法之外的其它方法 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    六.高级设置

    1.网页状态页

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

    只需要在location语句块下添加既可访问状态页    
    location /nginx_status {
       stub_status;
    }
    出于安全考虑应该为其添加验证模块
    
    location /nginx_status {
            stub_status;
            auth_basic    "xxxxx";
            auth_basic_user_file /apps/nginx/conf.d/.httpuser;
            //用户密码位置
            allow 127.0.0.1;
            deny all;
            //也可以只允许本机访问
     }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    2.第三方模块

    echo模块

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

    [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
    //重新编译安装
    
    //必须重启nginx服务使用
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    3.变量

    内置变量

    $remote_addr; 
    //存放了客户端的地址,注意是客户端的公网IP
    
    $proxy_add_x_forwarded_for
    //此变量表示将客户端IP追加请求报文中X-Forwarded-For首部字段,多个IP之间用逗号分隔
    
    $args; 
    //变量中存放了URL中的参数
    如:http://www.yyds.com/main/index.do?id=20190221&partner=search
    #返回结果为: id=20190221&partner=search  
    
    $document_root; 
    //保存了针对当前资源的请求的系统根目录,例如:/apps/nginx/html。
    
    
    
    $document_uri;
    //保存了当前请求中不包含参数的URI,注意是不包含请求的指令,比
    如:http://www.yyds.com/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为任意请求报文首部字段,表示记录请求报文的首部字段
    arbitrary request header field; the last part of a variable name is the field name converted to lower case with dashes replaced by underscores 
    //用下划线代替横线
      
    
    $http_user_agent; 
    //客户端浏览器的详细信息
    
    $http_cookie; 
    //客户端的cookie信息
    
    
    $cookie_
    //name为任意请求报文首部字部cookie的key名
    
    $http_
    //name为任意请求报文首部字段,表示记录请求报文的首部字段,ame的对应的首部字段名需要为小写,如果有
    横线需要替换为下划线
    arbitrary request header field; the last part of a variable name is the field 
    name converted to lower case with dashes replaced by underscores //用下划线代替横线
    
    
    
    $sent_http_
    //name为响应报文的首部字段,name的对应的首部字段名需要为小写,如果有横线需要替换为下划线,此变量有问题
    
    
    
    
    $arg_
    //此变量存放了URL中的指定参数,name为请求url中指定的参数
    //对比 变量  $arg  是全部,如果要id 如下$arg_id;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97

    自定义变量

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

    Syntax: set $variable value;
    Default: —
    Context: server, location, if
    
    • 1
    • 2
    • 3
    location /test {
            set $name  wwww;
            echo $name;
            //可以自定义一个变量
            set $my_port $server_port;
            echo $my_port;
            //也可以将内置变量赋值给另一个变量
            }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    4.自定义访问日志

    可自由指定日志格式

    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 之前 否则会不生效。
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    自定义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"}';
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    5.Nginx压缩功能

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

    压缩功能是依赖于模块 ngx_http_gzip_module

    //启用或禁用gzip压缩,默认关闭
    gzip on | off; 
    //压缩比由低到高从1到9,默认为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;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

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

     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;
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    6.https功能

    Web网站的登录页面都是使用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开启

    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
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    server {
     listen 80;
     listen 443 ssl;
     ssl_certificate /apps/nginx/conf.d/ssl/www.hh.com.crt;
     ssl_certificate_key /apps/nginx/conf.d/ssl/www.hh.com.key;
     ssl_session_cache shared:sslcache:20m;
     ssl_session_timeout 10m;
    }
    
    //所有证书要放一起
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    7.自定义图标

    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/hh/images;
         expires 365d;  //设置文件过期时间
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    七.重写功能

    Nginx服务器利用 ngx_http_rewrite_module 模块解析和处理rewrite请求,此功能依靠 PCRE(perl compatible regular expression),因此编译之前要安装PCRE库,rewrite是nginx服务器的重要功能之一,用于实现URL的重写,URL的重写是非常有用的功能,比如它可以在我们改变网站结构之后,不需要客户端修改原来的书签,也无需其他网站修改我们的链接,就可以设置为访问,另外还可以在一定程度上提高网站的安全性。

    1.if指令

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

    if (条件匹配) { 
     action
    }
    
    • 1
    • 2
    • 3

    使用正则表达式对变量进行匹配,匹配成功时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
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    
    location /main {
         index index.html;
         default_type text/html;
         if ( $scheme = http ){
           echo "if-----> $scheme";
         }
         if ( $scheme = https ){
          echo "if ----> $scheme";
       }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    2.return

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

    return code; //返回给客户端指定的HTTP状态码
    return code [text]; //返回给客户端的状态码及响应报文的实体内容,可以调用变量,其中text如果有空格,需要用单或双引号
    return code url; //返回给客户端的URL地址
    
    • 1
    • 2
    • 3
    server{
        listen 192.168.82.100:80;
        server_name www.hh.com;
        root /apps/nginx/html/hh;
        location /hh {
        default_type text/plain;
        return 666 "hello";
        //可以自定义防火门和文本
    }
    }
    
    
    server{
        listen 192.168.82.100:80;
        server_name www.hh.com;
        root /apps/nginx/html/hh;
        location /hh {
        default_type text/plain;
        return 302 http://www.baidu.com;
        //也可以实现302或者301重定向
    }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    3.set指令

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

    set $name yyds;
    set $my_port $server_port;
    
    • 1
    • 2
    4.break指令

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

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

    location /main {
       root /apps/nginx/html/hh;
       index index.html;
       default_type text/html;
        set $name yyds;
        echo $name;
       break;  //location块中break后面指令还会执行
        set $my_port $server_port;
        echo $my_port;
     }
     
     不会输出$my_port的内容
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    5.rewrite指令

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

    rewrite可以配置在 server、location、if

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

    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 这几个字母以外的任意字符
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    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
    
    • 1
    • 2
    • 3

    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
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    server{
        listen 192.168.82.100:80;
        server_name www.hh.com;
        root /apps/nginx/html/hh;
        location /hh {
        index index.html;
        rewrite /hh http://www.aa.com permanent;
    }
    }
    //当匹配到/hh时,实际跳转到www.aa.com/下的html
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    http 转https

    server {
     listen 443 ssl;
     listen 80;
     ssl_certificate /apps/nginx/certs/www.hh.com.crt;
     ssl_certificate_key /apps/nginx/certs/www.hh.com.key;
     ssl_session_cache shared:sslcache:20m;
     ssl_session_timeout 10m;
     server_name www.hh.com;
     location / {    //针对全站跳转
       root /apps/nginx/html/hh;
       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;
       }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    6.防盗链

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

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

    客户端机器

    yum install nginx
    cd /usr/share/nginx/html
    vim  test.html
    
    
    

    this is a web
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    实现防盗链

    location ~* \.(jpg|gif|swf)$ {            
             root  html;
             expires 1d;
             valid_referers none blocked *.hh.com  hh.com;   
             if ( $invalid_referer ) {
               rewrite ^/ http://www.hh.com/error.jpg;
               }
            }
            
    
    ~* \.(jpg|gif|swf)$:这段正则表达式表示匹配不区分大小写,以.jpg 或.gif 或.swf 结尾的文件
    Valid_referers:设置信任的网站,可以正常使用图片
    None :浏览器中 referer 为空的情况,就是直接在浏览器访问图片。
    Blocked :referer 不为空的情况 ,但是值被代理或防火墙删除了,这些值不以 http://或https://开头。后面的网址或者域名:referer 中包含相关字符串的网址
    If 语句:如果链接的来源域名不在 valid_referers 所列出的列表中,$invalid_referer 为true,则执行后面的操作,即进行重写或返回 403 页面。或者直接return 403;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    八.反向代理

    反向代理:reverse proxy,指的是代理外网用户的请求到内部的指定的服务器,并将数据返回给用户的一种方式,这是用的比较多的一种方式

    Nginx 除了可以在企业提供高性能的web服务之外,另外还可以将 nginx 本身不具备的请求通过某种预定义的协议转发至其它服务器处理,不同的协议就是Nginx服务器与其他服务器进行通信的一种规范,主要在不同的场景使用以下模块实现不同的功能

    ngx_http_proxy_module: //将客户端的请求以http协议转发至指定服务器进行处理
    ngx_http_upstream_module //用于定义为proxy_pass,fastcgi_pass,uwsgi_pass等指令引用的后
    端服务器分组
    ngx_stream_proxy_module://将客户端的请求以tcp协议转发至指定服务器处理
    ngx_http_fastcgi_module://将客户端对php的请求以fastcgi协议转发至指定服务器助理
    ngx_http_uwsgi_module: //将客户端对Python的请求以uwsgi协议转发至指定服务器处理
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    四层代理,基于ip端口,stream与http属于同级模块,通常用于负载均衡
    stream {
         upstream xx{
         ..........
         }
    }
    ...
    http{
    server {
    proxy_pass xx
    }
    }
    
    
    七层代理,基于协议,直接在http模块中,通常用于动静分离
    http{
    upstream xx{
    location ... {
    proxy_pass http://xx
    }
       }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    实现http反向代理
    proxy_pass; 
    //用来设置将客户端请求转发给的后端服务器的主机,可以是主机名(将转发至后端服务做为主机头首部)、IP
    地址:端口的方式
    //也可以代理到预先设置的主机群组,需要模块ngx_http_upstream_module支持
    
    server{
        listen 192.168.82.100:80;
        server_name www.hh.com;
        root /apps/nginx/html;
        location /hh {
        index index.html;
        proxy_pass  http://192.168.82.101;
    }
    
    //后面无uri,即无 / 符号,需要将location后面url 附加到proxy_pass指定的url后面,此行为类似于root
    //proxy_pass指定的uri不带斜线将访问的/hh,等于访问后端服务器
    http://192.168.82.101/hh/index.html,即后端服务器配置的站点根目录要有hh目录才可以被访问
    
    proxy_pass http://192.168.82.101/;   //后面有uri,即有 / 符号,相当于置换,即访问/hh时实际返回proxy_pass后面uri内容.此行为类似于alias 
    
    //如果location定义其uri时使用了正则表达式模式(包括~,~*,但不包括^~),则proxy_pass之后必须不能使用uri; 即不能有/ ,用户请求时传递的uri将直接附加至后端服务器之后
    
    server{
        listen 192.168.82.100:80;
        server_name www.hh.com;
        root /apps/nginx/html/hh;
        location ^~ /test {
        index index.html;
        proxy_pass  http://www.aa.com/;
    }
    }
    
    //^~可以匹配,可以使用/
    
    
    proxy_hide_header field;
    //用于nginx作为反向代理的时候,在返回给客户端http响应时,隐藏后端服务器相应头部的信息,可以设置
    在http,server或location块
    //示例: 隐藏后端服务器ETag首部字段
     location /hh {
       index index.html;
       proxy_pass http://192.168.82.101/; 
       proxy_hide_header ETag;
     }
     
     
     proxy_pass_header field;
    //默认nginx在响应报文中不传递后端服务器的首部字段Date, Server, X-Pad, X-Accel等参数,如果要传递的话则要使用 proxy_pass_header field声明将后端服务器返回的值传递给客户端
    //field 首部字段大小不敏感
    
    proxy_pass_request_body on | off; 
    //是否向后端服务器发送HTTP实体部分,可以设置在http,server或location块,默认即为开启
    
    
    proxy_pass_request_headers on | off; 
    //是否将客户端的请求头部转发给后端服务器,可以设置在http,server或location块,默认即为开启
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    将用户对域 www.hh.com的请求转发给后端服务器处理
    server{
        listen 192.168.82.100:80;
        server_name www.hh.com;
        root /apps/nginx/html;
        location  /hh {
        index index.html;
        proxy_pass  http://192.168.82.101;
    }
    }
    
    当访问www.hh.com/hh时,会进行反向代理,访问192.168.82.101下的hh
    可以在后面加/,直接访问后端根目录
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    指定localtion实现反向代理****
    server{
        listen 192.168.82.100:80;
        server_name www.hh.com;
        root /apps/nginx/html;
        location  /hh {
        index index.html;
        proxy_pass  http://192.168.82.101;
    }
        location  /aa {
        index index.html;
        proxy_pass  http://192.168.82.102;
    }
    }
    
    //可以将动态资源和静态资源分开在不同的后端服务器处理
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    缓存功能
    proxy_cache zone_name | off; 默认off
    //指明调用的缓存,或关闭缓存机制;Context:http, server, location
    //zone_name 表示缓存的名称.需要由proxy_cache_path事先定义
    
    proxy_cache_key string;
    //缓存中用于“键”的内容,默认值:proxy_cache_key $scheme$proxy_host$request_uri;
    
    
    proxy_cache_valid [code ...] time;
    //定义对特定响应码的响应内容的缓存时长,定义在http{...}中
    
    proxy_cache_path;
    //定义可用于proxy功能的缓存;Context:http   必须放在http语句中
    proxy_cache_path path [levels=levels] [use_temp_path=on|off] 
    keys_zone=zone_name:size [inactive=time] [max_size=size] [manager_files=number] 
    [manager_sleep=time] [manager_threshold=time] [loader_files=number] 
    [loader_sleep=time] [loader_threshold=time] [purger=on|off] 
    [purger_files=number] [purger_sleep=time] [purger_threshold=time];
    
    //示例:在http配置定义缓存信息
       proxy_cache_path /var/cache/nginx/proxy_cache #定义缓存保存路径,proxy_cache会自动创建
       levels=1:2:2 //定义缓存目录结构层次,1:2:2可以生成2^4x2^8x2^8=2^20=1048576个目录
       keys_zone=proxycache:20m //指内存中缓存的大小,主要用于存放key和metadata(如:使用次数),一般1M可存放8000个左右的key
       inactive=120s  //缓存有效时间  
       max_size=10g; //最大磁盘占用空间,磁盘存入文件内容的缓存空间最大值
       
    //调用缓存功能,需要定义在相应的配置段,如server{...};或者location等
    proxy_cache proxycache;
    proxy_cache_key $request_uri; //对指定的数据进行MD5的运算做为缓存的key
    proxy_cache_valid 200 302 301 10m; //指定的状态码返回的数据缓存多长时间
    proxy_cache_valid any 1m;   //除指定的状态码返回的数据以外的缓存多长时间,必须设置,否则不会缓存
    
    proxy_cache_use_stale error | timeout | invalid_header | updating | http_500 | http_502 | http_503 | http_504 | http_403 | http_404 | off ; //默认是off
    //在被代理的后端服务器出现哪种情况下,可直接使用过期的缓存响应客户端
    
    proxy_cache_methods GET | HEAD | POST ...;
    //对哪些客户端请求方法对应的响应进行缓存,GET和HEAD方法总是被缓存
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    http语段
    
    proxy_cache_path /data/nginx/proyxcache   levels=1:1:1 keys_zone=proxycache:20m inactive=120s max_size=1g;
    
    子配置文件server语段
    server{
            listen 80;
            server_name  www.hh.com;
            proxy_cache proxycache;
            proxy_cache_key $request_uri;
            #proxy_cache_key $host$uri$is_args$args;
            proxy_cache_valid 200 302 301 10m;
            proxy_cache_valid any 5m;
            root    /apps/nginx/html;
         location  / {
            root  /apps/nginx/html;
    }
         location  /api {
            root  /apps/nginx/html;
            proxy_pass http://192.168.82.101:80;
    
            }
         location ~* \.(jpg|jpeg|png|gif|bmp)$ {
            root  /apps/nginx/html;
            proxy_pass http://192.168.82.102;
            }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    反向代理客户端IP透传

    后端服务器的日志只会记录代理服务器的ip地址,所以无法统计出访问量

    这时需要实现IP透传,来记录真实客户端的ip地址

    server {
     listen 80;
     server_name www.hh.com;
     location / {
       index index.html index.php;
       root /data/nginx/html/hh;
       proxy_pass http://192.168.82.101;
       proxy_set_header X-Real-IP $remote_addr;                  //只添加客户端IP到请求报文头部,转发至后端服务器
       
     }
     }
     
     //当只有一台代理服务器时,可以返回客户端ip地址
     
     //当有多台代理服务器时,就会记录到前一台代理服务器的ip地址,无法实现IP透传,需要启用主配置中的日志格式才能使用$proxy_add_x_forwarded_for内置变量
     
     server {
     listen 80;
     server_name www.hh.com;
     location / {
       index index.html index.php;
       root /data/nginx/html/hh;
       proxy_pass http://192.168.82.101;
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
       //添加客户端IP和反向代理服务器IP到请求报文头部
     }
     }
     
     server {
     listen 80;
     server_name www.hh.com;
     location / {
       index index.html index.php;
       root /data/nginx/html/hh;
       proxy_pass http://192.168.82.100;
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
      //代理服务器的代理服务器 
     }
     }
     
     //所以每个代理服务器都要配置
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    负载均衡

    在上一个节中Nginx可以将客户端的请求转发至单台后端服务器但是无法转发至特定的一组的服务器,而且不能对后端服务器提供相应的服务器状态监测,Nginx 可以基于ngx_http_upstream_module模块提供服务器分组转发、权重分配、状态监测、调度算法等高级功能

    //自定义一组服务器,配置在http块内
    upstream   web { 
     [调度算法]
     server 192.168.82.102:[port];    
     server 192.168.82.101:[port];
    }
    
    location  / {
    pass_proxy  http://web/
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    server address [parameters];
    #配置一个后端web服务器,配置在upstream内,至少要有一个server服务器配置。
    #server支持的parameters如下:
    weight=number #设置权重,默认为1,实现类似于LVS中的WRR,WLC等
    max_conns=number  #给当前后端server设置最大活动链接数,默认为0表示没有限制
    max_fails=number  #后端服务器的下线条件,当客户端访问时,对本次调度选中的后端服务器连续进行检测多少次,如果都失败就标记为不可用,默认为1次,当客户端访问时,才会利用TCP触发对探测后端服务器健康性检查,而非周期性的探测
    fail_timeout=time #后端服务器的上线条件,对已经检测到处于不可用的后端服务器,每隔此时间间隔再次进行检测是否恢复可用,如果发现可用,则将后端服务器参与调度,默认为10秒
    backup  #设置为备份服务器,当所有后端服务器不可用时,才会启用此备用服务器 sorry server   自己不能转自己
    down    #标记为down状态
    resolve #当server定义的是主机名的时候,当A记录发生变化会自动应用新IP而不用重启Nginx
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    Nginx负载均衡策略

    1.轮询

    定义服务器组,对这组服务器进行轮询,进行轮流使用

    upstream   web { 
     server 192.168.82.102:[port];    
     server 192.168.82.101:[port];
    }
    
    • 1
    • 2
    • 3
    • 4

    2.ip_hash

    每个请求按访问IP的hash结果分配,同一个IP客户端固定访问一个后端服务器。可以保证来自同一ip的请求被打到固定的机器上,可以解决session问题。

    upstream   web { 
     ip_hash;  --同一个IP客户端固定访问一个后端服务器
     server 192.168.82.102:[port];    
     server 192.168.82.101:[port];
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    3.url_hash

    按访问url的hash结果来分配请求,使每个url定向到同一个后端服务器。一旦缓存住了资源,再次收到请求,就可以从缓存中读取。

    upstream   web { 
     hash $request_uri;  --实现每个url定向到同一个后端服务器
     server 192.168.82.102:[port];    
     server 192.168.82.101:[port];
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    4.least_conn

    把请求转发给连接数较少的后端服务器。轮询算法是把请求平均的转发给各个后端,使它们的负载大致相同;但是,有些请求占用的时间很长,会导致其所在的后端负载较高。这种情况下,least_conn这种方式就可以达到更好的负载均衡效果。

    upstream   web { 
     least_conn;  --把请求转发给连接数较少的后端服务器
     server 192.168.82.102:[port];    
     server 192.168.82.101:[port];
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    5.weight

    权重方式,在轮询策略的基础上指定轮询的比例。

    一般来说,性能好的服务器权重大,性能差的权重给小一些。

    upstream   web { 
     server 192.168.82.102:[port] weight=1;    
     server 192.168.82.101:[port] weight=2; --轮询的比例相对上一条要大
    }
    
    • 1
    • 2
    • 3
    • 4

    6.fair

    此种算法可以依据页面大小和加载时间长短智能地进行负载均衡,也就是根据后端服务器的响应时间来分配请求,响应时间短的优先分配。

    upstream   web { 
     fair;  --实现响应时间短的优先分配
     server 192.168.82.102:[port];    
     server 192.168.82.101:[port]; 
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
  • 相关阅读:
    oracle导入导出某个schema数据
    【毕业季·进击的技术er】青春不散场
    【接口测试】Postman(一)--接口测试知识准备
    LeetCode每日一题:1333. 餐厅过滤器(2023.9.27 C++)
    asp毕业设计——基于C#+asp.net+sqlserver作业审阅系统设计与实现(毕业论文+程序源码)——作业审阅系统
    jQuery基础教程
    就在刚刚 Kubernetes 1.25 正式发布,包括这些重大变化
    notepad++官网地址 https://notepad-plus-plus.org,notepad++使用教程
    [apue] 进程控制那些事儿
    文件包含漏洞(1),文件包含漏洞的利用原理
  • 原文地址:https://blog.csdn.net/q1231vev/article/details/133211180