高性能web服务器

web服务基础介绍

正常情况下单次 Web 服务访问流程
  1. 用户发起请求

当用户在浏览器中输入 URL(例如 `https://www.example.com`)并按下 Enter 键时,整个 Web 服务访问流程开始。

  1. DNS 域名解析

  2. **浏览器缓存检查**:浏览器首先检查本地缓存中是否有该域名对应的 IP 地址

  3. **操作系统缓存检查**:如果浏览器缓存中没有,检查操作系统缓存

  4. **路由器缓存检查**:如果操作系统缓存中没有,检查路由器缓存

  5. **ISP DNS 服务器查询**:如果以上都没有,向 ISP 的 DNS 服务器发起查询

  6. **递归/迭代查询**:DNS 服务器通过递归或迭代方式查询域名对应的 IP 地址

  7. **DNS 响应**:最终获得域名对应的 IP 地址并返回给浏览器

  8. TCP 连接建立(三次握手)

  9. **SYN**:客户端向服务器发送 SYN 包(同步序列编号),表示请求建立连接

  10. **SYN-ACK**:服务器收到 SYN 包后,发送 SYN-ACK 包(同步确认序列编号)

  11. **ACK**:客户端收到 SYN-ACK 包后,发送 ACK 包(确认编号),连接建立成功

  12. TLS/SSL 握手(HTTPS 协议)

如果使用 HTTPS 协议,还需要进行 TLS/SSL 握手:

  1. **客户端问候**:客户端发送支持的 TLS 版本、加密套件等信息

  2. **服务器问候**:服务器选择合适的 TLS 版本和加密套件,发送服务器证书

  3. **客户端验证**:客户端验证服务器证书的有效性

  4. **密钥交换**:客户端生成随机密钥,使用服务器公钥加密后发送

  5. **会话密钥生成**:服务器使用私钥解密,双方生成会话密钥

  6. **握手完成**:双方确认使用会话密钥进行加密通信

  7. HTTP 请求发送

浏览器构建 HTTP 请求报文并发送给服务器,请求报文包含:

  1. **请求行**:请求方法(GET/POST 等)、URL 路径、HTTP 版本

  2. **请求头**:Host、User-Agent、Accept 等

  3. **请求体**:对于 POST 等方法,包含提交的数据

  4. 服务器处理请求

服务器接收到 HTTP 请求后:

  1. **请求解析**:解析请求报文,提取请求方法、路径、参数等

  2. **路由处理**:根据 URL 路径找到对应的处理程序

  3. **业务逻辑**:执行相应的业务逻辑(如查询数据库、调用 API 等)

  4. **响应生成**:生成 HTTP 响应报文

  5. HTTP 响应返回

服务器发送 HTTP 响应报文给客户端,响应报文包含:

  1. **状态行**:HTTP 版本、状态码(200 OK、404 Not Found 等)、状态描述

  2. **响应头**:Content-Type、Content-Length、Set-Cookie 等

  3. **响应体**:HTML、JSON、图片等实际内容

  4. 浏览器渲染页面

浏览器接收到响应后:

  1. **解析 HTML**:构建 DOM 树

  2. **解析 CSS**:构建 CSSOM 树

  3. **JavaScript 执行**:执行内嵌或外部的 JavaScript 代码

  4. **渲染树构建**:结合 DOM 树和 CSSOM 树构建渲染树

  5. **布局计算**:计算每个元素的位置和大小

  6. **绘制页面**:将渲染树绘制到屏幕上

  7. **资源加载**:加载页面中的图片、字体等资源

  8. TCP 连接关闭(四次挥手)

  9. **FIN**:客户端发送 FIN 包,表示数据发送完毕,请求关闭连接

  10. **ACK**:服务器收到 FIN 包后,发送 ACK 包确认

  11. **FIN-ACK**:服务器发送 FIN 包,表示服务器也准备关闭连接

  12. **ACK**:客户端收到 FIN 包后,发送 ACK 包确认,连接关闭

  13. 完整流程总结

用户输入 URL → DNS 解析 → TCP 三次握手 → TLS/SSL 握手(HTTPS)→ 发送 HTTP 请求 → 服务器处理 → 返回 HTTP 响应 → 浏览器渲染 → TCP 四次挥手

客户访问nginx,nginx通过fpm给php,php处理完放到Memached内存中下次在用直接内存中取实现加速

web服务介绍

Achepa

Apache prefork 模型

预派生模式,有一个主控制进程,然后生成多个子进程,使用 select 模型,最大并发 1024
每个子进程有一个独立的线程响应用户请求
相对比较占用内存,但是比较稳定,可以设置最大和最小进程数
是最古老的一种模式 , 也是最稳定的模式,适用于访问量不是很大的场景
稳定但 每个用户请求需要对应开启一个进程 , 占用资源较多,并发性差 , 不适用于高并发场景
Apache worker 模型

一种多进程和多线程混合的模型
有一个控制进程,启动多个子进程
每个子进程里面包含固定的线程
使用线程程来处理请求
当线程不够使用的时候会再启动一个新的子进程 , 然后在进程里面再启动线程处理请求,
由于其使用了线程处理请求,因此可以承受更高的并发
优点:相比 prefork 占用的内存较少,可以同时处理更多的请求
缺点:使用 keepalive 的长连接方式,某个线程会一直被占据,即使没有传输数据,也需要一直等待到超时才会被释放。如果过多的线程,被这样占据,也会导致在高并发场景下的无服务线程可用(该问题在 prefork模式下,同样会发生)
Apache event 模型

Apache 中最新的模式, 2012 年发布的 apache 2.4.X 系列正式支持 event 模型 , 属于事件驱动模型 (epoll)
每个进程响应多个请求,在现在版本里的已经是稳定可用的模式
它和 worker 模式很像,最大的区别在于,它解决了 keepalive 场景下长期被占用的线程的资源浪费问题 (某些线程因为被keepalive ,空挂在哪里等待,中间几乎没有请求过来,甚至等到超时) event MPM 中,会有一个专门的线程来管理这些 keepalive 类型的线程 。当有真实请求过来的时候,将请求传递给服务线程,执行完毕后,又允许它释放。这样增强了高并发场景下的请求处理能力。
优点:单线程响应多请求,占据更少的内存,高并发下表现更优秀,会有一个专门的线程来管理 keepalive类型的线程,当有真实请求过来的时候,将请求传递给服务线程,执行完毕后,又允许它释放
缺点:没有线程安全控制

nginx

官网地址 www.nginx.org
nginx 以功能丰富著称,它即可以作为 http 服务 器,也可以作为反向代理服务器或者邮件服务器能够快速的响应静态网页的请求
适用高并发访问量大

服务端I/O流程

I/O在计算机中指Input/Output, IOPS (Input/Output Per Second)即每秒的输入输出量(或读写次数) ,是衡量磁盘性能的主要指标之一。IOPS 是指单位时间内系统能处理的 I/O 请求数量,一般以每秒处理的 I/O请求数量为单位, I/O 请求通常为读或写数据操作请求。
一次完整的I/O 是用户空间的进程数据与内核空间的内核数据的报文的完整交换,但是由于内核空间与用 户空间是严格隔离的,所以其数据交换过程中不能由用户空间的进程直接调用内核空间的内存数据,而 是需要经历一次从内核空间中的内存数据copy 到用户空间的进程内存当中,所以简单说 I/O 就是把数据从 内核空间中的内存数据复制到用户空间中进程的内存当中。

服务器的i/o类型:磁盘I/O和网络I/O

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

不论磁盘和网络 I/O
每次 I/O ,都要经由两个阶段:
第一步:将数据从文件先加载至内核内存空间(缓冲区),等待数据准备完成,时间较长
第二步:将数据从内核缓冲区复制到用户空间的进程的内存中,时间较短

I/O****模型相关概念

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

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

网络I/O模型

阻塞型、非阻塞型、信号驱动型、异步、复用型
内核不向应用发送好没好为同步,等待为阻塞

阻塞型I/O模型(blocking IO

(同步阻塞)

内核不告诉应用程序数据好了没,应用程序一直等待,内核不主动传输好没好,效率最低

非阻塞型I/O模型(noblocking IO

(同步非阻塞)

等待数据期间应用进程主动发起询问好没好,系统开销大,内核不主动传输好没好

信号驱动式I/O模型**(signal-driven IO)**

(异步阻塞模式)

异步I/O模型**(asynchronous IO)**

(异步非阻塞)全程不阻塞

默认是一个进程aio只能接受单个请求

多路复用I/O**(I/O multiplexing)**


主要包括 :select , poll , epoll 三种系统调用, select/poll/epoll 的好处就在于单个 process就可以同时处理多个网络连接的 IO 。

有一个记录每一个请求的表格,select一直遍历这个表格,那个好了完成那个

select缺点:表格有长度为1024

poll是长度无限大

epoll:那个好了直接告诉不用遍历
缺点:当连接数较少时效率相比多线程 + 阻塞 I/O 模型效率较低,可能延迟更大,因为单个连接处理需要 2 次系统调用,占用时间会有增加

零拷贝

零拷贝介绍

传统 Linux 中 I/O 的问题

1.访问请求从网络结课进来 2.内核拷贝请求到用户空间(第一次拷贝)3.用户nginx构建响应报文,没有向内核拿

4.内核访问硬盘那文件,复制到内核空间(第二次拷贝) 5.内核空间复制到用户(第三次)来构建响应报文

6.响应报文给内核(第四次) 7.内核给网络8.网络给用户

大量数据的拷贝,用户态和内核态的频繁切换,会消耗大量的 CPU 资源,严重影响数据传输的性

什么是零拷贝
零拷贝就是上述问题的一个解决方案,通过尽量避免拷贝操作来缓解 CPU 的压力。零拷贝并没有真正做到"0" 拷贝,它更多是一种思想,很多的零拷贝技术都是基于这个思想去做的优化

零拷页相关技术

MMAP ( Memory Mapping )

用户和内核之间构建直连的通道,避免了内核到用户的拷贝

SENDFILE

内核直接拷贝到Socket中,用户在Socket中构建响应报文

省了2次拷贝,内核到用户和用户到内核的

DMA 辅助的 SENDFILE

只有一次拷贝即,磁盘到Socke

需要有专业的硬件支持

Nginx

Nginx****介绍

Nginx 是免费的、开源的、高性能的 HTTP 和反向代理服务器、邮件代理服务器、以及 TCP/UDP 代理服务 器
Nginx 官网: http://nginx.org
nginx 的其它的二次发行版:
Tengine :由淘宝网发起的 Web 服务器项目。它在 Nginx 的基础上,针对大访问量网站的需求,添加
了很多高级功能和特性。 Tengine 的性能和稳定性已经在大型的网站如淘宝网,天猫商城等得到了
很好的检验。它的最终目标是打造一个高效、稳定、安全、易用的 Web 平台。从 2011 年 12 月开始, Tengine成为一个开源项目官网 : http://tengine.taobao.org/
OpenResty :基于 Nginx 与 Lua 语言的高性能 Web 平台, 章亦春团队开发,官网: http://openr
esty.org/cn/

Nginx的源码编译

1.下载
bash 复制代码
[root@Nginx ~]# wget https://nginx.org/download/nginx-1.28.1.tar.gz

https://nginx.org/download/nginx-1.28.1.tar.gz
2.解压
bash 复制代码
[root@Nginx ~]# tar zxf nginx-1.28.1.tar.gz
[root@Nginx ~]# cd nginx-1.28.1/
[root@Nginx nginx-1.28.1]# ls
auto     CHANGES.ru          conf       contrib          html     man        SECURITY.md
CHANGES  CODE_OF_CONDUCT.md  configure  CONTRIBUTING.md  LICENSE  README.md  src
3.检测环境
bash 复制代码
[root@nginx nginx-1.28.1]# ./configure --prefix=/usr/local/nginx \ #指定安装位置
> --user=nginx \
> --group=nginx \
> --with-http_ssl_module \
> --with-http_v2_module \
> --with-http_realip_module \
> --with-http_stub_status_module \
> --with-http_gzip_static_module \
> --with-pcre \
> --with-stream \
> --with-stream_ssl_module \
> --with-stream_realip_module

#根据检查的信息安装缺少的软件
checking for OpenSSL library in /opt/homebrew/ ... not found

./configure: error: SSL modules require the OpenSSL library.
You can either do not enable the modules, or install the OpenSSL library
into the system, or build the OpenSSL library statically from the source
with nginx by using --with-openssl=<path> option.

[root@nginx nginx-1.28.1]# dnf search OpenSSL 
bash 复制代码
#安装依赖性
[root@Nginx ~]# dnf install gcc openssl-devel.x86_64 pcre2-devel.x86_64 zlib-devel -y

[root@Nginx nginx-1.28.1]# ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module
4.编译
bash 复制代码
[root@Nginx nginx-1.28.1]# make     #检测完编译,在有Makefile的路径下执行make
[root@Nginx nginx-1.28.1]# make install #编译完安装
5.启动
bash 复制代码
#设定环境变量让系统找到nginx命令(直接执行nginx系统找不到,)
[root@Nginx sbin]# vim  ~/.bash_profile
export PATH=$PATH:/usr/local/nginx/sbin 
#表示执行的命令在原目录值上又多了一个目录名字,使识别添加目录中的命令
1.export

- 这是一个 Shell 内置命令
- 用于将变量导出为环境变量
- 环境变量可以被当前 Shell 及其子进程访问
- 如果不加 export ,变量仅在当前 Shell 中有效,子进程无法访问
2. PATH

- 这是 Linux 系统中最重要的环境变量之一
- 存储了系统查找可执行文件的目录列表
- 当您在命令行输入一个命令(如 ls 、 nginx )时,系统会按顺序在 PATH 列出的目录中查找该命令
3. $PATH

- $ 符号表示变量引用
- $PATH 表示读取 PATH 变量的当前值
- 这保留了原有的 PATH 内容,而不是覆盖它
4. : (冒号)

- 在 PATH 变量中,冒号是分隔符
- 用于分隔多个目录路径
- 例如: /usr/bin:/usr/local/bin:/home/user/bin
5. /usr/local/nginx/sbin

- 这是 Nginx 的可执行文件目录
- sbin 通常存放系统管理相关的二进制程序
- Nginx 的主程序 nginx 就在这个目录中

[root@Nginx sbin]# source   ~/.bash_profile

#指定使用nginx用户没有要创建
[root@Nginx logs]# useradd  -s /sbin/nologin -M nginx
[root@Nginx logs]# nginx
[root@Nginx logs]# ps aux | grep nginx
root       44012  0.0  0.1  14688  2356 ?        Ss   17:01   0:00 nginx: master process nginx
nginx      44013  0.0  0.2  14888  3892 ?        S    17:01   0:00 nginx: worker process
root       44015  0.0  0.1   6636  2176 pts/0    S+   17:01   0:00 grep --color=auto nginx


#测试
[root@Nginx logs]# echo timinglee > /usr/local/nginx/html/index.html

[root@Nginx logs]# curl  172.25.254.100
timinglee
6.编写启动文件

使其可以通过systemctl命令来管理

bash 复制代码
[root@Nginx ~]# vim /lib/systemd/system/nginx.service
[Unit]
Description=The NGINX HTTP and reverse proxy server
After=syslog.target network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking
ExecStartPre=/usr/local/nginx/sbin/nginx -t
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true

[Install]
WantedBy=multi-user.target

[root@Nginx ~]# systemctl daemon-reload

#验证
[root@Nginx ~]# systemctl status nginx.service
○ nginx.service - The NGINX HTTP and reverse proxy server
     Loaded: loaded (/usr/lib/systemd/system/nginx.service; disabled; preset: disabled)
     Active: inactive (dead)

[root@Nginx ~]# systemctl enable --now nginx
[root@Nginx ~]# ps aux | grep nginx
root        1839  0.0  0.1  14688  2356 ?        Ss   09:53   0:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx       1840  0.0  0.2  14888  3828 ?        S    09:53   0:00 nginx: worker process

[root@Nginx ~]# reboot
[root@Nginx ~]# systemctl status nginx.service

nginx的平滑升级和回滚

1.下载高版本的软件
复制代码
[root@Nginx ~]# wget https://nginx.org/download/nginx-1.29.4.tar.gz
2.对于新版本的软件进行源码编译并进行平滑升级
bash 复制代码
#编译nginx隐藏版本
[root@Nginx ~]# tar zxf nginx-1.29.4.tar.gz
[root@Nginx ~]# cd nginx-1.29.4/src/core/
[root@Nginx core]# vim nginx.h
#define nginx_version      1029004
#define NGINX_VERSION      ""
#define NGINX_VER          "TIMINGLEE/" NGINX_VERSION
#文件编辑完成后进行源码编译即可

[root@nginx nginx-1.29.4]# nginx -V
nginx version: nginx/1.28.1
built by gcc 11.5.0 20240719 (Red Hat 11.5.0-5) (GCC) 
built with OpenSSL 3.2.2 4 Jun 2024
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module


[root@Nginx core]# cd ../../
[root@Nginx nginx-1.29.4]# ./configure   --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module

[root@Nginx nginx-1.29.4]# make
[root@Nginx nginx-1.29.4]# cd objs/
[root@Nginx objs]# ls
autoconf.err  nginx    ngx_auto_config.h   ngx_modules.c  src
Makefile      nginx.8  ngx_auto_headers.h  ngx_modules.o


[root@Nginx objs]# cd /usr/local/nginx/sbin/
[root@Nginx sbin]# ls
nginx

[root@nginx sbin]# cp nginx nginx.old
[root@nginx sbin]# 

[root@Nginx sbin]# \cp -f /root/nginx-1.29.4/objs/nginx  /usr/local/nginx/sbin/nginx

[root@Nginx sbin]# ls /usr/local/nginx/logs/
access.log  error.log  nginx.pid


[root@Nginx sbin]# ps aux | grep nginx
root        1643  0.0  0.1  14688  2360 ?        Ss   09:55   0:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx       1644  0.0  0.2  14888  3896 ?        S    09:55   0:00 nginx: worker process

[root@Nginx sbin]# kill -USR2 1643   #nginx master进程id

[root@Nginx sbin]# ps aux | grep nginx
root        1643  0.0  0.1  14688  2744 ?        Ss   09:55   0:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx       1644  0.0  0.2  14888  3896 ?        S    09:55   0:00 nginx: worker process
root        4919  0.0  0.4  14716  7936 ?        S    10:24   0:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx       4921  0.0  0.2  14916  4156 ?        S    10:24   0:00 nginx: worker process
root        4923  0.0  0.1   6636  2176 pts/0    S+   10:25   0:00 grep --color=auto nginx

[root@Nginx sbin]# ls /usr/local/nginx/logs/
access.log  error.log  nginx.pid  nginx.pid.oldbin

#测试效果
[root@Nginx sbin]# nginx -V
nginx version: TIMINGLEE/
built by gcc 11.5.0 20240719 (Red Hat 11.5.0-5) (GCC)
built with OpenSSL 3.2.2 4 Jun 2024
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module


#回收旧版本子进程
[root@Nginx sbin]# ps aux | grep nginx
root        1643  0.0  0.1  14688  2744 ?        Ss   09:55   0:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx       1644  0.0  0.2  14888  3896 ?        S    09:55   0:00 nginx: worker process
root        4919  0.0  0.4  14716  7936 ?        S    10:24   0:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx       4921  0.0  0.2  14916  4156 ?        S    10:24   0:00 nginx: worker process
root        4929  0.0  0.1   6636  2176 pts/0    S+   10:27   0:00 grep --color=auto nginx
[root@Nginx sbin]# kill -WINCH 1643
[root@Nginx sbin]# ps aux | grep nginx
root        1643  0.0  0.1  14688  2744 ?        Ss   09:55   0:00 nginx: master process /usr/local/nginx/sbin/nginx
root        4919  0.0  0.4  14716  7936 ?        S    10:24   0:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx       4921  0.0  0.2  14916  4156 ?        S    10:24   0:00 nginx: worker process
root        4932  0.0  0.1   6636  2176 pts/0    S+   10:28   0:00 grep --color=auto nginx
3.版本回退|版本回滚
bash 复制代码
[root@Nginx sbin]# cd /usr/local/nginx/sbin/
[root@Nginx sbin]# cp nginx nginx.new -p
[root@Nginx sbin]# \cp nginx.old  nginx -pf
[root@Nginx sbin]# ps aux | grep nginx
root        1643  0.0  0.1  14688  2744 ?        Ss   09:55   0:00 nginx: master process /usr/local/nginx/sbin/nginx
root        4919  0.0  0.4  14716  7936 ?        S    10:24   0:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx       4921  0.0  0.2  14916  4156 ?        S    10:24   0:00 nginx: worker process

[root@Nginx sbin]# kill -HUP 1643
[root@Nginx sbin]# ps aux | grep nginx
root        1643  0.0  0.1  14688  2744 ?        Ss   09:55   0:00 nginx: master process /usr/local/nginx/sbin/nginx
root        4919  0.0  0.4  14716  7936 ?        S    10:24   0:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx       4921  0.0  0.2  14916  4156 ?        S    10:24   0:00 nginx: worker process
nginx       4963  0.0  0.2  14888  3896 ?        S    10:32   0:00 nginx: worker process
root        4965  0.0  0.1   6636  2176 pts/0    S+   10:32   0:00 grep --color=auto nginx
[root@Nginx sbin]# nginx -V
nginx version: nginx/1.28.1
built by gcc 11.5.0 20240719 (Red Hat 11.5.0-5) (GCC)
built with OpenSSL 3.2.2 4 Jun 2024
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module

#回收新版本进程
[root@Nginx sbin]# kill -WINCH 4919
[root@Nginx sbin]# ps aux | grep nginx
root        1643  0.0  0.1  14688  2744 ?        Ss   09:55   0:00 nginx: master process /usr/local/nginx/sbin/nginx
root        4919  0.0  0.4  14716  7936 ?        S    10:24   0:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx       4963  0.0  0.2  14888  3896 ?        S    10:32   0:00 nginx: worker process
root        4969  0.0  0.1   6636  2176 pts/0    S+   10:34   0:00 grep --color=auto nginx

Nginx配置文件的管理及优化参数

bash 复制代码
[root@Nginx ~]# vim /usr/local/nginx/conf/nginx.conf
user  nginx;

- 使用 vim 编辑器修改 Nginx 主配置文件
- 修改内容 :设置 user 指令为 nginx ,指定 Nginx 工作进程的运行用户
- 作用 :控制 Nginx worker 进程的权限级别,增强安全性
[root@Nginx ~]# nginx  -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

[root@Nginx ~]# nginx -s reload

[root@Nginx ~]# ps aux | grep nginx
root        5506  0.0  0.2  14564  3912 ?        Ss   14:40   0:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx       5511  0.0  0.2  14996  4032 ?        S    14:41   0:00 nginx: worker process
更改nginx子进程数量
bash 复制代码
[root@Nginx ~]# vim /usr/local/nginx/conf/nginx.conf
worker_processes  2;
[root@Nginx ~]# nginx -s reload
[root@Nginx ~]# ps aux | grep nginx
root        5506  0.0  0.2  14796  4040 ?        Ss   14:40   0:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx       5516  0.0  0.2  15012  4048 ?        S    14:42   0:00 nginx: worker process
nginx       5517  0.0  0.2  15012  4048 ?        S    14:42   0:00 nginx: worker process


#在vmware中更改硬件cpu核心个数,然后重启

[root@Nginx ~]# vim /usr/local/nginx/conf/nginx.conf
worker_processes  auto;
worker_cpu_affinity 0001 0010 0100 1000;

[root@Nginx ~]# ps aux | grep nginx
root         887  0.0  0.1  14564  2212 ?        Ss   14:51   0:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx        889  0.0  0.2  14964  3748 ?        S    14:51   0:00 nginx: worker process
nginx        890  0.0  0.2  14964  3748 ?        S    14:51   0:00 nginx: worker process
nginx        891  0.0  0.2  14964  3748 ?        S    14:51   0:00 nginx: worker process
nginx        892  0.0  0.2  14964  3748 ?        S    14:51   0:00 nginx: worker process


[root@Nginx ~]# ps axo pid,cmd,psr | grep nginx
    887 nginx: master process /usr/   3
   1635 nginx: worker process         0
   1636 nginx: worker process         1
   1637 nginx: worker process         2
   1638 nginx: worker process         3
设置每个进程最大连接数并修改限制
bash 复制代码
[root@Nginx ~]# vim /usr/local/nginx/conf/nginx.conf
events {
    worker_connections  10000;
    use epoll;
    accept_mutex on;
    multi_accept on;
}
- worker_connections 10000; :每个 worker 进程最大连接数
- use epoll; :使用 epoll 事件模型(Linux 平台最优选择)
- accept_mutex on; :开启连接互斥锁,避免惊群效应
- multi_accept on; :允许 worker 进程一次性接受多个连接
[root@Nginx ~]# nginx -s reload

#测试并发
[root@Nginx ~]# dnf install httpd-tools -y
安装 Apache Bench 工具(测试工具)
[root@Nginx ~]# ab  -n 100000 -c5000 http://172.25.254.100/index.html
This is ApacheBench, Version 2.3 <$Revision: 1913912 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 172.25.254.100 (be patient)
socket: Too many open files (24)				#并发数量过多导致访问失败
- 原因 :Linux 系统对每个进程可打开的文件描述符数量有限制
- 默认值 :通常为 1024 或更低
- 影响 :限制了进程可处理的并发连接数(每个连接需要一个文件描述符

#处理本地文件系统的并发文件数量
[root@Nginx ~]# vim /etc/security/limits.conf
*               -       nofile          100000
*               -       noproc          100000
root			-		nofile			100000
[root@Nginx ~]# sudo -u nginx ulimit -n
100000
[root@Nginx ~]# ulimit  -n 10000
100000

#测试
[root@Nginx ~]# ab  -n 100000 -c10000 http://172.25.254.100/index.html
This is ApacheBench, Version 2.3 <$Revision: 1913912 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 172.25.254.100 (be patient)
Completed 10000 requests
Completed 20000 requests
Completed 30000 requests
Completed 40000 requests
Completed 50000 requests

新建一个PCweb站点

1.location中的root

root :指定 web 的家目录,在定义 location 的时候,文件的绝对路径等于 root+location

bash 复制代码
[root@Nginx conf]# cd /usr/local/nginx/conf/
[root@Nginx conf]# mkdir  conf.d
[root@Nginx conf]# vim nginx.conf
82     include "/usr/local/nginx/conf/conf.d/*.conf";

[root@Nginx conf]# nginx -s reload
[root@Nginx conf]# cd conf.d/

[root@Nginx ~]# mkdir  -p /webdata/nginx/timinglee.org/lee/html
[root@Nginx ~]# echo lee.timinglee.org > /webdata/nginx/timinglee.org/lee/html/index.html

[root@Nginx conf.d]# vim vhosts.conf
server {
    listen 80;
    server_name lee.timinglee.org;
    location / {
        root /webdata/nginx/timinglee.org/lee/html;
    }
}

root@Nginx conf.d]# systemctl restart nginx.service

#测试
[root@Nginx conf.d]# vim /etc/hosts
172.25.254.100     Nginx www.timinglee.org lee.timinglee.org

[root@Nginx conf.d]# curl  www.timinglee.org
timinglee
[root@Nginx conf.d]# curl  lee.timinglee.org
lee.timinglee.org



#local示例需要访问lee.timinglee.org/lee/目录
[root@Nginx conf.d]# vim vhosts.conf
server {
    listen 80;
    server_name lee.timinglee.org;
    location / {
        root /webdata/nginx/timinglee.org/lee/html;
    }
    location /lee {			#lee标识location中的root值+location 后面指定的值代表目录的路径
        root /webdata/nginx/timinglee.org/lee/html;
    }
    
}

[root@Nginx conf.d]# systemctl restart nginx.service
[root@Nginx conf.d]# mkdir  -p /webdata/nginx/timinglee.org/lee/html/lee
[root@Nginx conf.d]# echo lee > /webdata/nginx/timinglee.org/lee/html/lee/index.html
[root@Nginx conf.d]# curl  lee.timinglee.org/lee/
lee
2.location中的alias

alias :定义路径别名,会把访问的路径重新定义到其指定的路径 , 文档映射的另一种机制 ; 仅能用于
location 上下文 , 此指令使用较少

bash 复制代码
[root@Nginx conf.d]# vim vhosts.conf
server {
    listen 80;
    server_name lee.timinglee.org;

    location /passwd {				#标识文件		
        alias /etc/passwd;
    }


    location /passwd/ {				#表示目录
        alias /mnt/;
    }

}

[root@Nginx conf.d]# nginx -s reload
[root@Nginx conf.d]# echo passwd > /mnt/index.html

#测试
[root@Nginx conf.d]# curl  lee.timinglee.org/passwd/
passwd
[root@Nginx conf.d]# curl  lee.timinglee.org/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
语法规则
bash 复制代码
#语法规则:
location [ = | ~ | ~* | ^~ ] uri { ... }
= #用于标准uri前,需要请求字串与uri精确匹配,大小敏感,如果匹配成功就停止向下匹配并
立即处理请求
^~ #用于标准uri前,表示包含正则表达式,并且匹配以指定的正则表达式开头
#对uri的最左边部分做匹配检查,不区分字符大小写
~ #用于标准uri前,表示包含正则表达式,并且区分大小写
~* #用于标准uri前,表示包含正则表达式,并且不区分大写
不带符号 #匹配起始于此uri的所有的uri
\ #用于标准uri前,表示包含正则表达式并且转义字符。可以将 . * ?等转义为普通符号
#匹配优先级从高到低:
=, ^~, ~/~*, 不带符号

KeepAlived长链接优化

配置

bash 复制代码
keepalive_timeout timeout [header_timeout]; #设定保持连接超时时长,0表示禁止长连
接,默认为75s
#通常配置在http字段作为站点全局配置

keepalive_requests 数字; #在一次长连接上所允许请求的资源的最大数量
#默认为100次,建议适当调大,比如:500

1.设定长链接时间

bash 复制代码
[root@Nginx ~]# vim /usr/local/nginx/conf/nginx.conf
keepalive_timeout   5;
[root@Nginx ~]# nginx -s reload

#测试
[root@Nginx ~]# dnf install telnet -y
[root@Nginx ~]# telnet www.timinglee.org 80
Trying 172.25.254.100...
Connected to www.timinglee.org.
Escape character is '^]'.
GET / HTTP/1.1     <<<<
Host: www.timinglee.org    <<<<
							<<<
HTTP/1.1 200 OK
Server: nginx/1.28.1
Date: Sat, 31 Jan 2026 08:27:02 GMT
Content-Type: text/html
Content-Length: 10
Last-Modified: Thu, 29 Jan 2026 09:02:15 GMT
Connection: keep-alive
ETag: "697b2217-a"
Accept-Ranges: bytes

timinglee    显示的页面出现后根据设定的长链接时间会等待,超过时间后会自动退出
Connection closed by foreign host.

2.设定长链接次数

bash 复制代码
[root@Nginx ~]# vim /usr/local/nginx/conf/nginx.conf
keepalive_requests 3;
[root@Nginx ~]# nginx -s reload

#测试
[root@Nginx ~]# telnet  www.timinglee.org 80
Trying 172.25.254.100...
Connected to www.timinglee.org.
Escape character is '^]'.
GET / HTTP/1.1
Host: www.timinglee.org

HTTP/1.1 200 OK					#第一次
Server: nginx/1.28.1
Date: Sat, 31 Jan 2026 08:32:14 GMT
Content-Type: text/html
Content-Length: 10
Last-Modified: Thu, 29 Jan 2026 09:02:15 GMT
Connection: keep-alive
Keep-Alive: timeout=100
ETag: "697b2217-a"
Accept-Ranges: bytes

timinglee
GET / HTTP/1.1
Host: www.timinglee.org

HTTP/1.1 200 OK				#第二次
Server: nginx/1.28.1
Date: Sat, 31 Jan 2026 08:32:24 GMT
Content-Type: text/html
Content-Length: 10
Last-Modified: Thu, 29 Jan 2026 09:02:15 GMT
Connection: keep-alive
Keep-Alive: timeout=100
ETag: "697b2217-a"
Accept-Ranges: bytes

timinglee
GET / HTTP/1.1
Host: www.timinglee.org

HTTP/1.1 200 OK			#第三次
Server: nginx/1.28.1
Date: Sat, 31 Jan 2026 08:32:35 GMT
Content-Type: text/html
Content-Length: 10
Last-Modified: Thu, 29 Jan 2026 09:02:15 GMT
Connection: close
ETag: "697b2217-a"
Accept-Ranges: bytes

timinglee
Connection closed by foreign host.

用户认证

bash 复制代码
[root@Nginx ~]# htpasswd  -cmb /usr/local/nginx/conf/.htpasswd admin  lee
Adding password for user admin

[root@Nginx ~]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
server {
    listen 80;
    server_name lee.timinglee.org;
    location /admin {
        root /usr/local/nginx/html;
        auth_basic "login passwd";
        auth_basic_user_file "/usr/local/nginx/conf/.htpasswd";
    }
}

[root@Nginx ~]# systemctl restart nginx.service

#测试:
root@Nginx ~]# curl  lee.timinglee.org/admin/
<html>
<head><title>401 Authorization Required</title></head>
<body>
<center><h1>401 Authorization Required</h1></center>
<hr><center>nginx/1.28.1</center>
</body>
</html>


[root@Nginx ~]# curl  -uadmin:lee http://lee.timinglee.org/admin/
admin

自定义错误页面

bash 复制代码
[root@Nginx ~]# mkdir  /usr/local/nginx/errorpage
[root@Nginx ~]# echo "太不巧了,你要访问的页面辞职了!!" > /usr/local/nginx/errorpage/errormessage
[root@Nginx ~]# cat /usr/local/nginx/errorpage/errormessage
太不巧了,你要访问的页面辞职了!!


[root@Nginx ~]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
server {
    listen 80;
    server_name lee.timinglee.org;
    error_page 404 405 503 502 /error;
    location /lee {
        root /usr/local/nginx/html;
    }

    location /error {
        alias /usr/local/nginx/errorpage/errormessage;
    }
}


[root@Nginx ~]# curl  lee.timinglee.org/lee/
太不巧了,你要访问的页面辞职了!!

自定义错误日志

bash 复制代码
[root@Nginx ~]# mkdir  -p /usr/local/nginx/logs/timinglee.org/
	[root@Nginx ~]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
	server {
    listen 80;
    server_name lee.timinglee.org;
    error_page 404 405 503 502 /error;
    error_log logs/timinglee.org/lee.error error;
    location /lee {
        root /usr/local/nginx/html;
    }

    location /error {
        alias /usr/local/nginx/errorpage/errormessage;
    }
}

[root@Nginx ~]# systemctl restart nginx.service

#测试
[root@Nginx ~]# cd  /usr/local/nginx/logs/timinglee.org/
[root@Nginx timinglee.org]# ls
lee.error
[root@Nginx timinglee.org]# cat lee.error
[root@Nginx timinglee.org]# curl  lee.timinglee.org/lee/
太不巧了,你要访问的页面辞职了!!
[root@Nginx timinglee.org]# cat lee.error
2026/02/01 11:10:57 [error] 2467#0: *1 "/usr/local/nginx/html/lee/index.html" is not found (2: No such file or directory), client: 172.25.254.100, server: lee.timinglee.org, request: "GET /lee/ HTTP/1.1", host: "lee.timinglee.org"

检测文件是否存在

如果不存在页面 , 就转到 default.HTML 页面

bash 复制代码
[root@Nginx ~]# echo default > /usr/local/nginx/errorpage/default.html
[root@Nginx ~]# cat /usr/local/nginx/errorpage/default.html
default


[root@Nginx ~]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
server {
    listen 80;
    server_name lee.timinglee.org;
    error_page 404 405 503 502 /error;
    error_log logs/timinglee.org/lee.error error;
    root /usr/local/nginx/errorpage;
    try_files $uri $uri.html $uri/index.html /default.html;
}

[root@Nginx ~]# nginx -s reload

#测试:
[root@Nginx ~]# curl -v  lee.timinglee.org/aaaaaaaaaa/
*   Trying 172.25.254.100:80...
* Connected to lee.timinglee.org (172.25.254.100) port 80 (#0)
> GET /aaaaaaaaaa/ HTTP/1.1
> Host: lee.timinglee.org
> User-Agent: curl/7.76.1
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Server: nginx/1.28.1
< Date: Sun, 01 Feb 2026 06:25:45 GMT
< Content-Type: text/html
< Content-Length: 8
< Last-Modified: Sun, 01 Feb 2026 06:17:57 GMT
< Connection: keep-alive
< Keep-Alive: timeout=100
< ETag: "697ef015-8"
< Accept-Ranges: bytes
<
default
* Connection #0 to host lee.timinglee.org left intact

Nginx中建立下载服务器

1.启用列表功能
bash 复制代码
[root@Nginx ~]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
server {
    listen 80;
    server_name lee.timinglee.org;
    error_page 404 405 503 502 /error;
    error_log logs/timinglee.org/lee.error error;
    location /lee {
        root /usr/local/nginx/html;
    }

    location /error {
        alias /usr/local/nginx/errorpage/errormessage;
    }


    location /download {
        root /usr/local/nginx;
        autoindex on;
    }
}
[root@Nginx ~]# nginx -s reload
2.下载控速
bash 复制代码
[root@Nginx ~]# wget http://lee.timinglee.org/download/bigfile
--2026-02-01 11:37:52--  http://lee.timinglee.org/download/bigfile
正在解析主机 lee.timinglee.org (lee.timinglee.org)... 172.25.254.100
正在连接 lee.timinglee.org (lee.timinglee.org)|172.25.254.100|:80... 已连接。
已发出 HTTP 请求,正在等待回应... 200 OK
长度:104857600 (100M) [application/octet-stream]
正在保存至: "bigfile"

bigfile                  100%[=================================>] 100.00M   232MB/s  用时 0.4s

2026-02-01 11:37:52 (232 MB/s) - 已保存 "bigfile" [104857600/104857600])

[root@Nginx ~]# rm -fr bigfile

[root@Nginx ~]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
server {
    listen 80;
    server_name lee.timinglee.org;
    error_page 404 405 503 502 /error;
    error_log logs/timinglee.org/lee.error error;
    location /lee {
        root /usr/local/nginx/html;
    }

    location /error {
        alias /usr/local/nginx/errorpage/errormessage;
    }


    location /download {
        root /usr/local/nginx;
        autoindex on;
        limit_rate 1024k;
    }
}
[root@Nginx ~]# nginx -s reload

[root@Nginx ~]# wget http://lee.timinglee.org/download/bigfile
--2026-02-01 11:39:09--  http://lee.timinglee.org/download/bigfile
正在解析主机 lee.timinglee.org (lee.timinglee.org)... 172.25.254.100
正在连接 lee.timinglee.org (lee.timinglee.org)|172.25.254.100|:80... 已连接。
已发出 HTTP 请求,正在等待回应... 200 OK
长度:104857600 (100M) [application/octet-stream]
正在保存至: "bigfile"

bigfile                   12%[===>                              ]  12.00M  1.00MB/s  剩余 88s
3.显示文件大小优化
bash 复制代码
[root@Nginx ~]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
server {
    listen 80;
    server_name lee.timinglee.org;
    error_page 404 405 503 502 /error;
    error_log logs/timinglee.org/lee.error error;
    location /lee {
        root /usr/local/nginx/html;
    }

    location /error {
        alias /usr/local/nginx/errorpage/errormessage;
    }


    location /download {
        root /usr/local/nginx;
        autoindex on;
        limit_rate 1024k;
        autoindex_exact_size off;
    }
}
[root@Nginx ~]# nginx -s reload

效果

bash 复制代码
root@Nginx ~]# curl  lee.timinglee.org/download
<html>
<head><title>301 Moved Permanently</title></head>
<body>
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.28.1</center>
</body>
</html>
[root@Nginx ~]# curl  lee.timinglee.org/download/
<html>
<head><title>Index of /download/</title></head>
<body>
<h1>Index of /download/</h1><hr><pre><a href="../">../</a>
<a href="bigfile">bigfile</a>                                            01-Feb-2026 03:28    100M
<a href="passwd">passwd</a>                                             01-Feb-2026 03:27    1294
</pre><hr></body>
</html>
4.时间显示调整
bash 复制代码
[root@Nginx ~]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
server {
    listen 80;
    server_name lee.timinglee.org;
    error_page 404 405 503 502 /error;
    error_log logs/timinglee.org/lee.error error;
    location /lee {
        root /usr/local/nginx/html;
    }

    location /error {
        alias /usr/local/nginx/errorpage/errormessage;
    }


    location /download {
        root /usr/local/nginx;
        autoindex on;
        limit_rate 1024k;
        autoindex_exact_size off;
        autoindex_localtime on;
    }
}
[root@Nginx ~]# nginx -s reload
5.设定页面风格
bash 复制代码
[root@Nginx ~]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
server {
    listen 80;
    server_name lee.timinglee.org;
    error_page 404 405 503 502 /error;
    error_log logs/timinglee.org/lee.error error;
    location /lee {
        root /usr/local/nginx/html;
    }

    location /error {
        alias /usr/local/nginx/errorpage/errormessage;
    }


    location /download {
        root /usr/local/nginx;
        autoindex on;
        limit_rate 1024k;
        autoindex_exact_size off;
        autoindex_localtime on;
        autoindex_format html | xml | json | jsonp;
    }
}
[root@Nginx ~]# nginx -s reload

练习

bash 复制代码
[root@Nginx ~]# vim /usr/local/nginx/conf/conf.d/vhosts.conf 
1 server{
   2     listen 80;
   3     server_name xier.xierxier.org;
   4     error_page 404 405 503 502 /error;
   5     #error log
   6     error_log logs/xierxier.org/xier.error error;
   7     #file check
   8     root /usr/local/nginx/errorpage;
   9     try_files $uri $uri.html $uri/index.html /default.html;
  10     location / {
  11     root    /usr/local/nginx/xier.org/xier/html;
  12     auth_basic  "login passwd";
  13     auth_basic_user_file    "/usr/local/nginx/conf/.htpasswd";
  14     }
  15     location /error{
  16     alias /usr/local/nginx/errorpage/errormessage;
  17     }
  18     location /download {
  19     root    /usr/local/nginx;
  20     autoindex    on;
  21     limit_rate   1024k;
  22     autoindex_exact_size off;
  23     autoindex_localtime on;
  24     autoindex_format  xml;
  25     #| xml | jsonp;
  26     }
  27 }

nginx高级配置

Nginx的状态页

bash 复制代码
[root@Nginx ~]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
server {
    listen 80;
    server_name lee.timinglee.org;

    location /nginx_status{
        stub_status;
        auth_basic "auth login";  #用户认证
        auth_basic_user_file /usr/local/nginx/conf/.htpasswd;#用户认证
        allow 172.25.254.0/24;
        deny all;
    }
}

[root@Nginx ~]# nginx -s reload

Nginx的压缩功能

bash 复制代码
[root@Nginx ~]# mkdir  /usr/local/nginx/timinglee.org/lee/html -p
[root@Nginx ~]# echo  hello lee > /usr/local/nginx/timinglee.org/lee/html/index.html


[root@Nginx ~]# vim /usr/local/nginx/conf/nginx.conf
  40行左右  gzip  on;
    gzip_comp_level 4;
    gzip_disable "MSIE [1-6]\.";
    gzip_min_length 1024k;
    gzip_buffers 32 1024k
    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;
    gzip_static on;
    
    
[root@Nginx ~]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
server {
    listen 80;
    server_name lee.timinglee.org;
    root /usr/local/nginx/timinglee.org/lee/html;
    location /nginx_status{
        stub_status;
        auth_basic "auth login";
        auth_basic_user_file /usr/local/nginx/conf/.htpasswd;
        allow 172.25.254.0/24;
        deny all;
    }
}

[root@Nginx ~]# nginx -s reload


#测试
[root@nginx ~]# cp /usr/local/nginx/logs/access.log  /webdate/nginx/xier.org/xier/html/bigfile.txt 
[root@nginx ~]# nginx -s reload
[root@nginx ~]# curl -uadmin:lee xier.xierxier.org
xier.xierxier.org
[root@nginx ~]# curl --head --compressed  -uadmin:lee xier.xierxier.org
HTTP/1.1 200 OK
Server: nginx/1.28.1
Date: Sun, 01 Feb 2026 09:03:31 GMT
Content-Type: text/html
Content-Length: 18
Last-Modified: Sat, 31 Jan 2026 08:18:55 GMT
Connection: keep-alive
ETag: "697dbaef-12"
Accept-Ranges: bytes

[root@nginx ~]# curl --head --compressed  -uadmin:lee xier.xierxier.org/bigfile.txt
HTTP/1.1 200 OK
Server: nginx/1.28.1
Date: Sun, 01 Feb 2026 09:03:54 GMT
Content-Type: text/plain
Last-Modified: Sun, 01 Feb 2026 09:02:05 GMT
Connection: keep-alive
Vary: Accept-Encoding
ETag: W/"697f168d-14ac853"
Content-Encoding: gzip

Nginx****的版本隐藏

bash 复制代码
[root@Nginx nginx-1.26.1]# vim src/core/nginx.h
#define nginx_version 1026001
#define NGINX_VERSION "1.0"
#define NGINX_VER "HAHA/" NGINX_VERSION

Nginx 变量

1.升级Nginx支持echo

bash 复制代码
[root@Nginx ~]# systemctl stop nginx.service
[root@Nginx ~]# ps aux | grep nginx
root        5193  0.0  0.1   6636  2176 pts/1    S+   16:08   0:00 grep --color=auto nginx


[root@Nginx ~]# tar zxf echo-nginx-module-0.64.tar.gz
[root@Nginx ~]# cd nginx-1.28.1/

[root@Nginx nginx-1.28.1]# make clean

[root@Nginx nginx-1.28.1]# ./configure  --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module  --add-module=/root/echo-nginx-module-0.64

[root@Nginx nginx-1.28.1]# make
[root@Nginx nginx-1.28.1]# rm -rf /usr/local/nginx/sbin/nginx
[root@Nginx nginx-1.28.1]# cp objs/nginx /usr/local/nginx/sbin/ -p

#测试
[root@Nginx nginx-1.28.1]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
server {
    listen 80;
    server_name lee.timinglee.org;
    root /usr/local/nginx/timinglee.org/lee/html;
    location /vars {
        default_type text/html;
        echo $remote_addr;
    }
}

[root@Nginx nginx-1.28.1]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful


[root@Nginx nginx-1.28.1]# systemctl start nginx.service

2.理解内建变量

bash 复制代码
```bash
[root@Nginx nginx-1.28.1]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
server {
    listen 80;
    server_name lee.timinglee.org;
    root /usr/local/nginx/timinglee.org/lee/html;
    location /vars {
        default_type text/html;
        echo $remote_addr;
    }
}

[root@Nginx nginx-1.28.1]# nginx -s reload
[root@Nginx nginx-1.28.1]# curl  lee.timinglee.org/vars/
172.25.254.100
```

```bash
[root@Nginx nginx-1.28.1]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
server {
    listen 80;
    server_name lee.timinglee.org;
    root /usr/local/nginx/timinglee.org/lee/html;
    location /vars {
        default_type text/html;
        echo $args;
    }
}

[root@Nginx nginx-1.28.1]# nginx -s reload
[root@Nginx nginx-1.28.1]# curl "http://lee.timinglee.org/vars?key=lee&id=11"
key=lee&id=11
```

```
[root@Nginx nginx-1.28.1]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
server {
    listen 80;
    server_name lee.timinglee.org;
    root /usr/local/nginx/timinglee.org/lee/html;
    location /vars {
        default_type text/html;
        echo $args;
       	echo $is_args;
    }
}

[root@Nginx nginx-1.28.1]# nginx -s reload
[root@Nginx nginx-1.28.1]# curl "http://lee.timinglee.org/vars?key=lee&id=11"
172.25.254.100
key=lee&id=11
?
[root@Nginx nginx-1.28.1]# curl "http://lee.timinglee.org/vars"
172.25.254.100
```

```bash
[root@Nginx nginx-1.28.1]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
server {
    listen 80;
    server_name lee.timinglee.org;
    root /usr/local/nginx/timinglee.org/lee/html;
    location /vars {
        default_type text/html;
        echo $document_root;
    }
}

[root@Nginx nginx-1.28.1]# nginx -s reload

[root@Nginx nginx-1.28.1]# curl "http://lee.timinglee.org/vars?key=lee&id=11"
/usr/local/nginx/timinglee.org/lee/html

```

```bash
[root@Nginx nginx-1.28.1]# vim /usr/local/nginx/conf/conf.d/vhosts.conf    
    listen 80;
    server_name lee.timinglee.org;
    root /usr/local/nginx/timinglee.org/lee/html;
    location /vars {
        default_type text/html;
        echo $remote_addr;
        echo $args;
        echo $is_args;
        echo $document_root;
        echo $document_uri;
        echo $host;
        echo $remote_port;
        echo $remote_user;
        echo $request_method;
        echo $request_filename;
        echo $request_uri;
        echo $scheme;
        echo $server_protocol;
        echo $server_addr;
        echo $server_name;
        echo $server_port;
        echo $http_user_agent;
        echo $cookie_key2;
        echo $http_user_agent;
        echo $sent_http_content_type;
    }
}

[root@Nginx nginx-1.28.1]# nginx -s reload
[root@Nginx nginx-1.28.1]# curl -b "key1=hello,key2=timinglee" -A "haha" -ulee:lee "http://lee.timinglee.org/vars?key=lee&id=11"
172.25.254.100
key=lee&id=11
?
/usr/local/nginx/timinglee.org/lee/html
/vars
lee.timinglee.org
45156
lee
GET
/usr/local/nginx/timinglee.org/lee/html/vars
/vars?key=lee&id=11
http
HTTP/1.1
172.25.254.100
lee.timinglee.org
80
haha
timinglee
haha
text/html
```

自定义变量

bash 复制代码
[root@Nginx ~]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
server {
    listen 80;
    server_name lee.timinglee.org;
    root /usr/local/nginx/timinglee.org/lee/html;
    location /vars {
        default_type text/html;
        #功能 :设置默认的 MIME 类型 参数 : text/html 是 MIME 类型,表示 HTML 文本 作用 :当 Nginx 无法根据文件扩展名确定内容类型时,使用这个默认类型 说明 :在这个 location 中,所有响应都会被标记为 HTML 类型,无论实际内容是什么
     
        set $test lee;					#手动设定变量值
     	echo $test;
        set $web_port $server_port;		#变量个传递
        echo $web_port;
    }
}

[root@Nginx ~]# nginx -s reload
[root@Nginx ~]# curl  lee.timinglee.org/vars/
lee
80

**Nginx Rewrite 相关功能(**网页从写

1.网页重写中的指令

if

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

bash 复制代码
= #比较变量和字符串是否相等,相等时if指令认为该条件为true,反之为false
!= #比较变量和字符串是否不相等,不相等时if指令认为条件为true,反之为false
~ #区分大小写字符,可以通过正则表达式匹配,满足匹配条件为真,不满足匹配条件为假
!~ #区分大小写字符,判断是否匹配,不满足匹配条件为真,满足匹配条件为假
~* #不区分大小写字符,可以通过正则表达式匹配,满足匹配条件为真,不满足匹配条件为假
!~* #不区分大小字符,判断是否匹配,满足匹配条件为假,不满足匹配条件为真
-f 和 !-f #判断请求的文件是否存在和是否不存在
-d 和 !-d #判断请求的目录是否存在和是否不存在
-x 和 !-x #判断文件是否可执行和是否不可执行
-e 和 !-e #判断请求的文件或目录是否存在和是否不存在(包括文件,目录,软链接)
#注意:
#如果$变量的值为空字符串或0,则if指令认为该条件为false,其他条件为true。
#nginx 1.0.1之前$变量的值如果以0开头的任意字符串会返回false
bash 复制代码
#if
[root@Nginx ~]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
server {
    listen 80;
    server_name lee.timinglee.org;
    root /webdir/timinglee.org/lee/html;
    location /vars {
        echo $remote_user;
        echo $request_method;
        echo $request_filename;
        echo $request_uri;
        echo $scheme;
    }

    location / {
        if ( $http_user_agent ~* firefox ) {
            return 200 "test if messages";
        }
    }
}

[root@Nginx ~]# nginx -s reload
[root@Nginx ~]# curl  lee.timinglee.org
lee page

[root@Nginx ~]# curl  -A "firefox" lee.timinglee.org
test if messages[root@Nginx ~]#

set

bash 复制代码
#set
[root@Nginx ~]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
server {
    listen 80;
    server_name lee.timinglee.org;
    root /webdir/timinglee.org/lee/html;
    location /vars {
        echo $remote_user;
        echo $request_method;
        echo $request_filename;
        echo $request_uri;
        echo $scheme;
    }

    location / {
        set $testname timinglee;
        echo $testname;
    }
}

[root@Nginx ~]# nginx -s reload

[root@Nginx ~]# curl  lee.timinglee.org
timinglee

return

bash 复制代码
#return
[root@Nginx ~]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
server {
    listen 80;
    server_name lee.timinglee.org;
    root /webdir/timinglee.org/lee/html;
    location /vars {
        echo $remote_user;
        echo $request_method;
        echo $request_filename;
        echo $request_uri;
        echo $scheme;
    }

    location / {
        return 200 "hello world";
    }
}
[root@Nginx ~]# nginx -s reload
[root@Nginx ~]# curl  lee.timinglee.org
hello world

break

bash 复制代码
#break
[root@Nginx ~]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
server {
    listen 80;
    server_name lee.timinglee.org;
    root /webdir/timinglee.org/lee/html;
    location /vars {
        echo $remote_user;
        echo $request_method;
        echo $request_filename;
        echo $request_uri;
        echo $scheme;
    }

    location / {
        set $test1 lee1;
        set $test2 lee2;
        if ($http_user_agent = firefox){
            break;
        }
        set $test3 lee3;
        echo $test1 $test2 $test3;
    }
}
[root@Nginx ~]# nginx -s reload

[root@Nginx ~]# curl  lee.timinglee.org
lee1 lee2 lee3
[root@Nginx ~]# curl -A "firefox" lee.timinglee.org
lee1 lee2

rewrite重定向

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

2.rewrite flag****使用介绍

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

redirect

bash 复制代码
[root@Nginx ~]# vim /usr/local/nginx/conf/conf.d/vhosts.conf

server {
    listen 80;
    server_name lee.timinglee.org;
    root /webdir/timinglee.org/lee/html;
    location /vars {
        echo $remote_user;
        echo $request_method;
        echo $request_filename;
        echo $request_uri;
        echo $scheme;
    }

    location / {
        rewrite / http://www.baidu.com redirect;
    }
}
[root@Nginx ~]# nginx -s reload

[root@Nginx ~]# curl -I lee.timinglee.org
HTTP/1.1 302 Moved Temporarily			#定向方式返回值
Server: nginx/1.28.1
Date: Tue, 03 Feb 2026 02:43:47 GMT
Content-Type: text/html
Content-Length: 145
Connection: keep-alive
Keep-Alive: timeout=100
Location: http://www.baidu.com			#定向效果

permanent

bash 复制代码
[root@Nginx ~]# vim /usr/local/nginx/conf/conf.d/vhosts.conf

server {
    listen 80;
    server_name lee.timinglee.org;
    root /webdir/timinglee.org/lee/html;
    location /vars {
        echo $remote_user;
        echo $request_method;
        echo $request_filename;
        echo $request_uri;
        echo $scheme;
    }

    location / {
        rewrite / http://www.baidu.com permanent;
    }
}
[root@Nginx ~]# nginx -s reload


[root@Nginx ~]# curl  -I lee.timinglee.org
HTTP/1.1 301 Moved Permanently #返回值
Server: nginx/1.28.1
Date: Tue, 03 Feb 2026 02:45:38 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive
Keep-Alive: timeout=100
Location: http://www.baidu.com

break

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

last

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

bash 复制代码
#break 和 last
[root@Nginx ~]# mkdir  /webdir/timinglee.org/lee/html/{break,last,test1,test2}
[root@Nginx ~]# echo break > /webdir/timinglee.org/lee/html/break/index.html
[root@Nginx ~]# echo last > /webdir/timinglee.org/lee/html/last/index.html
[root@Nginx ~]# echo test1 > /webdir/timinglee.org/lee/html/test1/index.html
[root@Nginx ~]# echo test2 > /webdir/timinglee.org/lee/html/test2/index.html

#break
[root@Nginx ~]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
server {
    listen 80;
    server_name lee.timinglee.org;
    root /webdir/timinglee.org/lee/html;
    location /vars {
        echo $remote_user;
        echo $request_method;
        echo $request_filename;
        echo $request_uri;
        echo $scheme;
    }

    location /break {
        rewrite /break/(.*) /test1/$1 break;
        rewrite /test1 /test2;
    }
    location /test1 {
        return 200 "test1 end page";
    }
    location /test2 {
        return 200 "TEST2 END PAGE";
    }

}

root@Nginx ~]# nginx -s reload
[root@Nginx ~]# curl  -L lee.timinglee.org/break/index.html
test1


#last
[root@Nginx ~]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
server {
    listen 80;
    server_name lee.timinglee.org;
    root /webdir/timinglee.org/lee/html;
    location /vars {
        echo $remote_user;
        echo $request_method;
        echo $request_filename;
        echo $request_uri;
        echo $scheme;
    }

    location /break {
        rewrite /break/(.*) /test1/$1 last;
        rewrite /test1 /test2;
    }
    location /test1 {
        return 200 "test1 end page";
    }
    location /test2 {
        return 200 "TEST2 END PAGE";
    }

}

root@Nginx ~]# nginx -s reload
[root@Nginx ~]# curl  -L lee.timinglee.org/break/index.html
test1 end page

Nginx利用网页重写实现全站加密

1.制作key

bash 复制代码
[root@Nginx ~]# openssl req -newkey rsa:2048 -nodes  -sha256  -keyout  /usr/local/nginx/certs/timinglee.org.key -x509 -days 365 -out /usr/local/nginx/certs/timinglee.org.crt


[root@nginx ~]# mkdir -p /usr/local/nginx/certs/
[root@nginx ~]# openssl req -newkey rsa:2048 -nodes -sha256 -keyout /usr/local/nginx/certs/xier.org.key -x509 -days 365 -out /usr/local/nginx/certs/xier.org.crt

2.编辑加密配置文件

bash 复制代码
[root@nginx ~]# cd /usr/local/nginx/conf/conf.d/

[root@nginx conf.d]# vim ssl_https.conf.bak 
处理 /root/.vimrc 时发生错误:
第    3 行:
E488: Trailing characters: set relativenumber: #set relativenumber
请按 ENTER 或其它命令继续
   1 server {
   2   listen 80;
   3   listen 443 ssl;
   4   ssl_certificate /usr/local/nginx/certs/xier.org.crt;
   5   ssl_certificate_key /usr/local/nginx/certs/xier.org.key;
   6   ssl_session_cache shared:sslcache:20m;
   7   ssl_session_timeout 10m;
   8   server_name www.xier.com;
   9   location / {
  10     if ( $scheme = http ) {
  11           rewrite /(.*) https://$host/$1 redirect;
  12             }
  13         }
  14     }

[root@nginx conf.d]# mv WEBrewrite.conf WEBrewrite.conf.bak
[root@nginx conf.d]# vim ssl_https.conf 
[root@nginx conf.d]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@nginx conf.d]# nginx -s reload
[root@nginx conf.d]# curl -I http://www.xier.com/xier
HTTP/1.1 302 Moved Temporarily
Server: nginx/1.28.1
Date: Tue, 03 Feb 2026 23:17:26 GMT
Content-Type: text/html
Content-Length: 145
Connection: keep-alive
Location: https://www.xier.com/xier

[root@nginx conf.d]# 

nginx防盗链

1.编辑子配置文件

bash 复制代码
[root@nginx conf.d]# vim anti-leeching.conf
[root@nginx conf.d]# nginx -s reload
[root@nginx conf.d]# vim anti-leeching.conf

  13 server {
  12     listen 80;
  11     server_name www.xier.com;
  10     root /webdir/xier.org/xier/html;
   9     location / {
   8         valid_referers none blocked server_names *.xier.com ~/baidu/.;
#- 通配符只能出现在最左侧 :例如 *.example.com 是有效的
#- 通配符必须完整匹配一个域名标签 :通配符 * 只能代表一个完整的子域名部分,不能跨 . 分隔符
#- 不支持中间或右侧的通配符 :例如 *.xier.* 或 example.* 都是无效的
#~\.xier\. 是正则表达式,表示匹配包含 .xier. 的任何域名(如 www.xier.com 、 img.xier.cn 等)
   7         if ($invalid_referer){
   6             return 404;
   5             }
   4         }
   3     location /img {
   2         valid_referers none blocked server_names *.xier.com ~/baidu/.;
   1         if ($invalid_referer){
14               rewrite ^/ http://www.xier.com/img/xier.jpg;
   1             }
   2         }
   3     }
#  rewrite ^/ http://www.xier.com/img/xier.jpg;和 location /img 目录不能一样否则会导致无限循环使不能查看图片

上面代码由于目录一样无限循环打不开图片改为下面配置

bash 复制代码
10 server {
   9     listen 80;
   8     server_name www.xier.com;
   7     root /webdir/xier.org/xier/html;
   6     location / {
   5         valid_referers none blocked server_names *.xier.com ~/baidu/.;
   4         if ($invalid_referer){
   3             return 404;
   2             }
   1         }
11       location /png {
   1         valid_referers none blocked server_names *.xier.com ~/baidu/.;
   2         if ($invalid_referer){
   3             rewrite ^/ http://www.xier.com/img/xier.jpg;
   4             }
   5         }
   6     }
   [root@nginx conf.d]# mkdir /webdir/xier.org/xier/html/png
[root@nginx conf.d]# nginx -s reload

2.测试效果

Nginx反向代理

1.实验环境

bash 复制代码
#172.25.254.10 RS1	172.25.254.20 RS2


[root@RSX ~]# dnf install httpd -y
[root@RSX ~]# systemctl enable --now httpd
[root@RSX ~]# echo 172.25.254.20 > /var/www/html/index.html


#测试 在Nginx主机中
[root@Nginx ~]# curl  172.25.254.10
172.25.254.10
[root@Nginx ~]# curl  172.25.254.20
172.25.254.20

2.简单的代理方法

proxy_pass; # 用来设置将客户端请求转发给的后端服务器的主机

可以是主机名 ( 将转发至后端服务做为主机头首部 ) 、 IP 地址:端口的方式

也可以代理到预先设置的主机群组,需要模块 ngx_http_upstream_module 支持

bash 复制代码
[root@RS2 ~]# mkdir  /var/www/html/web
[root@RS2 ~]# echo 172.25.254.20 web > /var/www/html/web/index.html


[root@Nginx ~]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
server {
    listen 80;
    server_name lee.timinglee.org;
    location / {
        proxy_pass http://172.25.254.10:80;
    }

    location /web {
        proxy_pass http://172.25.254.20:80;
    }

}


[root@Nginx ~]# nginx -s reload

#测试
[root@Nginx ~]# curl  172.25.254.20/web/
172.25.254.20 web
[root@Nginx ~]# curl  172.25.254.10
172.25.254.10

3.proxy_hide_header filed

proxy_hide_header field; # 用于 nginx 作为反向代理的时候

在返回给客户端 http 响应时

隐藏后端服务器相应头部的信息

可以设置在 http,server 或 location 块

bash 复制代码
[Administrator.DESKTOP-VJ307M3] ➤ curl -v lee.timinglee.org
*   Trying 172.25.254.100:80...
* TCP_NODELAY set
* Connected to lee.timinglee.org (172.25.254.100) port 80 (#0)
> GET / HTTP/1.1
> Host: lee.timinglee.org
> User-Agent: curl/7.65.0
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Server: nginx/1.28.1
< Date: Tue, 03 Feb 2026 06:31:03 GMT
< Content-Type: text/html; charset=UTF-8
< Content-Length: 14
< Connection: keep-alive
< Keep-Alive: timeout=100
< Last-Modified: Tue, 03 Feb 2026 06:20:50 GMT
< ETag: "e-649e570e8a49f"					#可以看到ETAG信息
< Accept-Ranges: bytes
<
172.25.254.10
* Connection #0 to host lee.timinglee.org left intact

[root@Nginx ~]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
server {
    listen 80;
    server_name lee.timinglee.org;
    location / {
        proxy_pass http://172.25.254.10:80;
        proxy_hide_header ETag;
    }

    location /web {
        proxy_pass http://172.25.254.20:80;
    }

}
[root@Nginx ~]# nginx -s reload

#测试
[Administrator.DESKTOP-VJ307M3] ➤ curl -v lee.timinglee.org
*   Trying 172.25.254.100:80...
* TCP_NODELAY set
* Connected to lee.timinglee.org (172.25.254.100) port 80 (#0)
> GET / HTTP/1.1
> Host: lee.timinglee.org
> User-Agent: curl/7.65.0
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Server: nginx/1.28.1
< Date: Tue, 03 Feb 2026 06:33:11 GMT
< Content-Type: text/html; charset=UTF-8
< Content-Length: 14
< Connection: keep-alive
< Keep-Alive: timeout=100
< Last-Modified: Tue, 03 Feb 2026 06:20:50 GMT
< Accept-Ranges: bytes
<
172.25.254.10

4.proxy_pass_heade

proxy_pass_header field; # 透传

默认 nginx 在响应报文中不传递后端服务器的首部字段 Date, Server, X-Pad, X-Accel 等参数

如果要传递的话则要使用 proxy_pass_header field 声明将后端服务器返回的值传递给客户端

#field 首部字段大小不敏感

bash 复制代码
[Administrator.DESKTOP-VJ307M3] ➤ curl -v lee.timinglee.org
*   Trying 172.25.254.100:80...
* TCP_NODELAY set
* Connected to lee.timinglee.org (172.25.254.100) port 80 (#0)
> GET / HTTP/1.1
> Host: lee.timinglee.org
> User-Agent: curl/7.65.0
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Server: nginx/1.28.1						#默认访问不透传server信息
< Date: Tue, 03 Feb 2026 06:35:35 GMT
< Content-Type: text/html; charset=UTF-8
< Content-Length: 14
< Connection: keep-alive
< Keep-Alive: timeout=100
< Last-Modified: Tue, 03 Feb 2026 06:20:50 GMT
< Accept-Ranges: bytes
<
172.25.254.10
* Connection #0 to host lee.timinglee.org left intact

[root@Nginx ~]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
server {
    listen 80;
    server_name lee.timinglee.org;
    location / {
        proxy_pass http://172.25.254.10:80;
        proxy_pass_header Server;
    }

    location /web {
        proxy_pass http://172.25.254.20:80;
    }

}

[root@Nginx ~]# nginx -s reload
Administrator.DESKTOP-VJ307M3] ➤ curl -v lee.timinglee.org
*   Trying 172.25.254.100:80...
* TCP_NODELAY set
* Connected to lee.timinglee.org (172.25.254.100) port 80 (#0)
> GET / HTTP/1.1
> Host: lee.timinglee.org
> User-Agent: curl/7.65.0
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Date: Tue, 03 Feb 2026 06:37:25 GMT
< Content-Type: text/html; charset=UTF-8
< Content-Length: 14
< Connection: keep-alive
< Keep-Alive: timeout=100
< Server: Apache/2.4.62 (Red Hat Enterprise Linux)			#透传结果
< Last-Modified: Tue, 03 Feb 2026 06:20:50 GMT
< Accept-Ranges: bytes
<
172.25.254.10
* Connection #0 to host lee.timinglee.org left intact

透传信息

可更改或添加客户端的请求头部信息内容并转发至后端服务器,比如在后端服务器想要获取客户端的真实 IP的时候,就要更改每一个报文的头部

bash 复制代码
[root@RS1 ~]# vim /etc/httpd/conf/httpd.conf
    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" \"%{X-Forwarded-For}i\"" combined


[root@RS1 ~]# systemctl restart httpd

[root@Nginx ~]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
server {
    listen 80;
    server_name lee.timinglee.org;
    location / {
        proxy_pass http://172.25.254.10:80;
        proxy_set_header X-Forwarded-For $remote_addr;

    }

    location /web {
        proxy_pass http://172.25.254.20:80;
    }

[root@Nginx ~]# nginx -s reload

[Administrator.DESKTOP-VJ307M3] ➤ curl  lee.timinglee.org
172.25.254.10


[root@RS1 ~]# cat /etc/httpd/logs/access_log
172.25.254.100 - - [03/Feb/2026:14:47:37 +0800] "GET / HTTP/1.0" 200 14 "-" "curl/7.65.0" "172.25.254.1"

利用反向代理实现动静分离(针对特定资源实现代理)

1.实验环境

bash 复制代码
#在10中
[root@RS1 ~]# dnf install php -y
[root@RS1 ~]# systemctl restart httpd

[root@RS1 ~]# vim /var/www/html/index.php
<?php
    echo "<h2>172.25.254.10</h2>";
    phpinfo();
?>

2.动静分离的实现

bash 复制代码
[root@Nginx ~]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
server {
    listen 80;
    server_name lee.timinglee.org;
    location / {
        proxy_pass http://172.25.254.20:80;

    }

    location ~* \.(php|js)$ {
        proxy_pass http://172.25.254.10:80;
    }

}
[root@Nginx ~]# nginx -s reload

缓存加速

1.当未启用缓存时进行压测

bash 复制代码
[Administrator.DESKTOP-VJ307M3] ➤ ab -n 10000 -c 50 lee.timinglee.org/index.php
This is ApacheBench, Version 2.3 <$Revision: 1807734 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking lee.timinglee.org (be patient)
Completed 1000 requests
Completed 2000 requests
Completed 3000 requests
Completed 4000 requests
Completed 5000 requests
Completed 6000 requests
Completed 7000 requests
Completed 8000 requests
Completed 9000 requests
Completed 10000 requests
Finished 10000 requests


Server Software:        nginx/1.28.1
Server Hostname:        lee.timinglee.org
Server Port:            80

Document Path:          /index.php
Document Length:        72921 bytes

Concurrency Level:      50
Time taken for tests:   13.678 seconds
Complete requests:      10000
Failed requests:        9963				#失败的
   (Connect: 0, Receive: 0, Length: 9963, Exceptions: 0)
Total transferred:      731097819 bytes
HTML transferred:       729237819 bytes
Requests per second:    731.10 [#/sec] (mean)
Time per request:       68.390 [ms] (mean)
Time per request:       1.368 [ms] (mean, across all concurrent requests)
Transfer rate:          52197.72 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    7   4.0      6      26
Processing:     4   61 168.8     44    3405
Waiting:        2   38 129.9     26    3316
Total:          5   68 168.7     51    3405

Percentage of the requests served within a certain time (ms)
  50%     51
  66%     61
  75%     68
  80%     71
  90%     83
  95%     92
  98%    105
  99%    506
 100%   3405 (longest request)

2.设定缓存加速

bash 复制代码
[root@Nginx ~]# vim /usr/local/nginx/conf/nginx.conf
proxy_cache_path /usr/local/nginx/proxy_cache levels=1:2:2 keys_zone=proxycache:20m inactive=120s max_size=1g;

proxy_cache_path /usr/local/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=1g; #最大磁盘占用空间,磁盘存入文件内容的缓存空间最大值

编辑子配置文件:
server {
    listen 80;
    server_name lee.timinglee.org;
    location / {
        proxy_pass http://172.25.254.20:80;

    }

    location ~* \.(php|js)$ {
        proxy_pass http://172.25.254.10:80;
        proxy_cache proxycache;
        proxy_cache_key $request_uri;
        proxy_cache_valid 200 302 301 10m;
        proxy_cache_valid any 1m;
    }

}


[root@Nginx ~]# systemctl restart nginx.service
[root@Nginx ~]# tree  /usr/local/nginx/proxy_cache/
/usr/local/nginx/proxy_cache/

0 directories, 0 files

#测试
[Administrator.DESKTOP-VJ307M3] ➤ ab -n 10000 -c 50 lee.timinglee.org/index.php
This is ApacheBench, Version 2.3 <$Revision: 1807734 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking lee.timinglee.org (be patient)
Completed 1000 requests
Completed 2000 requests
Completed 3000 requests
Completed 4000 requests
Completed 5000 requests
Completed 6000 requests
Completed 7000 requests
Completed 8000 requests
Completed 9000 requests
Completed 10000 requests
Finished 10000 requests


Server Software:        nginx/1.28.1
Server Hostname:        lee.timinglee.org
Server Port:            80

Document Path:          /index.php
Document Length:        72925 bytes

Concurrency Level:      50
Time taken for tests:   4.365 seconds
Complete requests:      10000
Failed requests:        0
Total transferred:      731110000 bytes
HTML transferred:       729250000 bytes
Requests per second:    2290.76 [#/sec] (mean)
Time per request:       21.827 [ms] (mean)
Time per request:       0.437 [ms] (mean, across all concurrent requests)
Transfer rate:          163554.31 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    4   1.8      4      11
Processing:     4   18  31.3     15     734
Waiting:        1    9  30.7      5     726
Total:          6   22  31.2     20     734

Percentage of the requests served within a certain time (ms)
  50%     20
  66%     21
  75%     21
  80%     22
  90%     27
  95%     32
  98%     41
  99%     46
 100%    734 (longest request)
            
            
[root@Nginx ~]# tree  /usr/local/nginx/proxy_cache/
/usr/local/nginx/proxy_cache/
└── 1
    └── af
        └── 15
            └── e251273eb74a8ee3f661a7af00915af1

3 directories, 1 file

反向代理负载均衡

Nginx 可以基于 ngx_http_upstream_module 模块提供服务器分组转发、权重分配、状态监测、调度算法等高级功能
官方文档: https://nginx.org/en/docs/http/ngx_http_upstream_module.html
http upstream 独立于http模块

1.实验环境

172.25.254.100 #Nginx 代理服务器

172.25.254.10 #后端web A,Apache部署

172.25.254.20 #后端web B,Apache部署

2.实现负载均衡

bash 复制代码
[root@Nginx ~]# mkdir  /usr/local/nginx/conf/upstream/
[root@Nginx ~]# vim /usr/local/nginx/conf/nginx.conf
events {
    worker_connections  10000;
    use epoll;
    accept_mutex on;
    multi_accept on;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
	include "/usr/local/nginx/conf/upstream/*.conf";		#子配置目录


[root@Nginx ~]# vim /usr/local/nginx/conf/upstream/loadbalance.conf
upstream webserver {
    server 172.25.254.10:80 weight=1 fail_timeout=15s max_fails=3;
    server 172.25.254.20:80 weight=1 fail_timeout=15s max_fails=3;
    server 172.25.254.100:8888 backup;

}
server {
    listen 80;
    server_name www.timinglee.org;

    location ~ / {
        proxy_pass http://webserver;
    }
}



[root@Nginx ~]# mkdir  /webdir/timinglee.org/error/html -p
[root@Nginx ~]# echo error > /webdir/timinglee.org/error/html/index.html

[root@Nginx ~]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
server {
    listen 8888;
    root /webdir/timinglee.org/error/html;
}


#测试:
[root@Nginx ~]# curl www.timinglee.org
172.25.254.10
[root@Nginx ~]# curl www.timinglee.org
172.25.254.20
[root@Nginx ~]# curl www.timinglee.org
172.25.254.10
[root@Nginx ~]# curl www.timinglee.org
172.25.254.20
[root@Nginx ~]# curl www.timinglee.org
172.25.254.20
[root@Nginx ~]# curl www.timinglee.org
172.25.254.20


[root@RS1+2 ~]# systemctl stop httpd

[root@Nginx ~]# curl www.timinglee.org
error

Nginx负载均衡算法

1.ip_hash;

源地址 hash 调度方法,基于的客户端的 remote_addr( 源地址 IPv4 的前 24 位或整个 IPv6 地址 ) 做 hash 计算,以实现会话保持

即根据客户端ip进行调度

2.hash $request_uri consistent;

#基于用户请求的uri做hash

即访问路径进行调度

3.least_conn;

最少连接调度算法,优先将客户端请求调度到当前连接最少的后端服务器 , 相当于 LVS 中的 WLC

4.hash $cookie_sessionid

基于 cookie 中的 sessionid 这个 key 进行 hash 调度 , 实现会话

绑定

bash 复制代码
[root@Nginx ~]# vim /usr/local/nginx/conf/upstream/loadbalance.conf
upstream webserver {
    #ip_hash;
    #hash $request_uri consistent;
    #least_conn;
    hash $cookie_lee;
    server 172.25.254.10:80 weight=1 fail_timeout=15s max_fails=3;
    server 172.25.254.20:80 weight=1 fail_timeout=15s max_fails=3;
    #server 172.25.254.100:8888 backup;

}
server {
    listen 80;
    server_name www.timinglee.org;

    location ~ / {
        proxy_pass http://webserver;
    }
}



#
[root@Nginx ~]# curl  -b lee=20 www.timinglee.org
[root@Nginx ~]# curl   www.timinglee.org/web1/index.html
[root@Nginx ~]# curl   www.timinglee.org/

Nginx的四层负载均衡代理

1.实验环境搭建(Mysql)

在RS1和RS2上

bash 复制代码
[root@RS1 ~]# dnf install mariadb-server -y
[root@RS1 ~]# vim /etc//my.cnf.d/mariadb-server.cnf 
···
  16 [mysqld]
  17 server-id=10
···
[root@RS1 ~]# systemctl enable --now mariadb
[root@RS1 ~]# mysql
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 3
Server version: 10.5.27-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> CREATE USER xier@'%' IDENTIFIED BY 'xier';
//- CREATE USER :创建新用户的SQL语句
//- xier@'%' :
//- xier :用户名
//- @'%' :主机名部分, % 表示允许从任何IP地址连接
//- IDENTIFIED BY 'xier' :设置用户密码为'xier'
Query OK, 0 rows affected (0.001 sec)

MariaDB [(none)]> GRANT ALL ON *.* TO xier@'%';
- GRANT :授予权限的SQL语句
- ALL :授予所有权限(包括SELECT、INSERT、UPDATE、DELETE等)
- ON *.* :
- 第一个 * :表示所有数据库
- 第二个 * :表示所有表
- TO xier@'%' :将权限授予xier用户,允许从任何主机连接
Query OK, 0 rows affected (0.001 sec)

MariaDB [(none)]> quit
Bye
[root@RS1 ~]# 

tcp四层负载

bash 复制代码
[root@nginx ~]# mkdir /usr/local/nginx/conf/tcpudp -p
[root@nginx conf]# vim /usr/local/nginx/conf/nginx.conf
···
 140 include "/usr/local/nginx/conf/tcpudp/*.conf";
···
[root@nginx conf]# vim /usr/local/nginx/conf/tcpudp/tcpudp.conf
   1 stream {
   2   upstream mysql_server {
   3     server 172.25.254.10:3306 max_fails=3 fail_timeout=30s;
   4     server 172.25.254.20:3306 max_fails=3 fail_timeout=30s;
   5     }
   6   server {
   7     listen 172.25.254.100:3306;
   8     proxy_pass mysql_server;
   9     proxy_connect_timeout 30s;
  10     proxy_timeout 300s;
  11     }
  12 }

[root@nginx conf]# nginx -t
[root@nginx conf]# nginx -s reload

注意

bash 复制代码
Nginx 配置文件有严格的层级结构,主要包括以下几个部分(按顺序):

1. 全局块 - 包含运行用户、工作进程数等配置
2. events 块 - 包含连接处理相关配置
3. http 块 - 包含 HTTP 服务器相关配置
4. stream 块 - 包含 TCP/UDP 流代理相关配置(与 http 块同级)
### 关键问题
stream 指令必须在主配置文件的顶层 ,与 http 块同级,而不是在 http 块内部

测试

bash 复制代码
[root@windows ~]# dnf install mysql -y

[root@windows ~]# mysql -uxier -pxier -h172.25.254.100
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.5.5-10.5.27-MariaDB MariaDB Server

Copyright (c) 2000, 2025, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> SELECT @@server_id;
+-------------+
| @@server_id |
+-------------+
|          10 |
+-------------+
1 row in set (0.00 sec)

mysql> quit
Bye
[root@windows ~]# mysql -uxier -pxier -h172.25.254.100
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.5.5-10.5.27-MariaDB MariaDB Server

Copyright (c) 2000, 2025, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> SELECT @@server_id;
+-------------+
| @@server_id |
+-------------+
|          20 |
+-------------+
1 row in set (0.01 sec)

mysql> quit
Bye

2.实验环境搭建(dns)

bash 复制代码
[root@RS1 ~]# dnf install bind -y
[root@RS1 ~]# vim /etc/named.conf 
···
  10 options {
  11 //  listen-on port 53 { 127.0.0.1; };
  12 //  listen-on-v6 port 53 { ::1; };
  13     directory   "/var/named";
  14     dump-file   "/var/named/data/cache_dump.db";
  15     statistics-file "/var/named/data/named_stats.txt";
  16     memstatistics-file "/var/named/data/named_mem_stats.txt";
  17     secroots-file   "/var/named/data/named.secroots";
  18     recursing-file  "/var/named/data/named.recursing";
  19 //  allow-query     { localhost; };
···
  33     dnssec-validation no;
···
[root@RS1 ~]# vim /etc/named.rfc1912.zones 
···
  27 };
  28 
  29 zone "xier.org" IN {
  30     type master;
  31     file "xier.org.zone";
  32     allow-update { none; };
  33 };
···
[root@RS1 named]# cd /var/named/
[root@RS1 named]# cp -p named.localhost xier.org.zone
[root@RS1 named]# vim xier.org.zone 
   1 $TTL 1D
   2 @   IN SOA  dns.xier.org. rname.invalid. (
   3                     0   ; serial
   4                     1D  ; refresh
   5                     1H  ; retry
   6                     1W  ; expire
   7                     3H )    ; minimum
   8         NS  dns.xier.org.
   9 dns     A   172.25.254.10

[root@RS2 named]# vim xier.org.zone 
   1 $TTL 1D
   2 @   IN SOA  dns.xier.org. rname.invalid. (
   3                     0   ; serial
   4                     1D  ; refresh
   5                     1H  ; retry
   6                     1W  ; expire
   7                     3H )    ; minimum
   8         NS  dns.xier.org.
   9 dns     A   172.25.254.20
#理论上应设置的和RS1一样,看实验效果所以设置的不一样
[root@RS1 named]# systemctl enable --now named.service 

测试

bash 复制代码
[root@RS1 named]# dig dns.xier.org @172.25.254.10

; <<>> DiG 9.16.23-RH <<>> dns.xier.org @172.25.254.10
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 33160
;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 1232
; COOKIE: 1986afab60f2b4d7010000006988941663f87a420fb2bd63 (good)
;; QUESTION SECTION:
;dns.xier.org.			IN	A

;; ANSWER SECTION:
dns.xier.org.		86400	IN	A	172.25.254.10

;; Query time: 0 msec
;; SERVER: 172.25.254.10#53(172.25.254.10)
;; WHEN: Sun Feb 08 21:48:06 CST 2026
;; MSG SIZE  rcvd: 85

[root@RS2 named]# dig dns.xier.org @172.25.254.20

; <<>> DiG 9.16.23-RH <<>> dns.xier.org @172.25.254.20
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 36491
;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 1232
; COOKIE: 4b882185b51cfad9010000006988945deaec14efe482c21b (good)
;; QUESTION SECTION:
;dns.xier.org.			IN	A

;; ANSWER SECTION:
dns.xier.org.		86400	IN	A	172.25.254.20

;; Query time: 1 msec
;; SERVER: 172.25.254.20#53(172.25.254.20)
;; WHEN: Sun Feb 08 21:49:17 CST 2026
;; MSG SIZE  rcvd: 85
bash 复制代码
**`dig`** - 命令本身
- **全称**: Domain Information Groper(域名信息查询器)
- **用途**: 用于查询DNS名称服务器的灵活工具
- **类型**: 外部命令(属于`bind-utils`或`dnsutils`软件包)
- **功能**: 执行DNS查找并显示从查询的名称服务器返回的答案

**`dns.xier.org`** - 查询目标
- **类型**: 完全限定域名(FQDN)
- **用途**: 正在查询的域名
- **结构**:
  - `dns` - 子域名
  - `xier` - 二级域名
  - `org` - 顶级域名(TLD)
- **默认查询类型**: A记录(IPv4地址)

**`@172.25.254.10`** - DNS服务器指定
- **`@`符号**: 表示要查询的DNS服务器(而不是使用系统默认的DNS服务器)
- **172.25.254.10**: 要查询的DNS服务器的IP地址
- **类型**: 私有IP地址(可能在本地网络或实验室环境中)
- **用途**: 直接将查询定向到此DNS服务器,绕过`/etc/resolv.conf`设置

udp四层负载

bash 复制代码
[root@nginx conf]# vim /usr/local/nginx/conf/tcpudp/tcpudp.conf
  
 1 stream {
   2   upstream mysql_server {
   3     server 172.25.254.10:3306 max_fails=3 fail_timeout=30s;
   4     server 172.25.254.20:3306 max_fails=3 fail_timeout=30s;
   5     }
   6 
   7   upstream dns_server {
   8     server 172.25.254.10:53 max_fails=3 fail_timeout=30s;
   9     server 172.25.254.20:53 max_fails=3 fail_timeout=30s;
  10     }
  11     
  12   server { 
  13     listen 172.25.254.100:3306;
  14     proxy_pass mysql_server;
  15     proxy_connect_timeout 30s;
  16     proxy_timeout 300s;
  17     }
  18     
  19   server { 
  20     listen 172.25.254.100:53 udp;
  21     proxy_pass dns_server;
  22     proxy_timeout 1s;
  23     proxy_responses 1;
#使用udp协议时,设置代理服务器响应客户端期望的数据报文数,作为会话终止条件
  24     error_log logs/dns.log;
  25     }
  26 
  27 }

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

测试

bash 复制代码
[root@windows ~]# 
[root@windows ~]# dig dns.xier.org @172.25.254.100

; <<>> DiG 9.16.23-RH <<>> dns.xier.org @172.25.254.100
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 6688
;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 1232
; COOKIE: df14be911a349a8b010000006988a7fae9f0a0f7950f1829 (good)
;; QUESTION SECTION:
;dns.xier.org.			IN	A

;; ANSWER SECTION:
dns.xier.org.		86400	IN	A	172.25.254.10

;; Query time: 1 msec
;; SERVER: 172.25.254.100#53(172.25.254.100)
;; WHEN: Sun Feb 08 23:12:58 CST 2026
;; MSG SIZE  rcvd: 85

[root@windows ~]# dig dns.xier.org @172.25.254.100

; <<>> DiG 9.16.23-RH <<>> dns.xier.org @172.25.254.100
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 1451
;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 1232
; COOKIE: 8f8a0d762e311d2f010000006988a802d1c884797dc7b7f9 (good)
;; QUESTION SECTION:
;dns.xier.org.			IN	A

;; ANSWER SECTION:
dns.xier.org.		86400	IN	A	172.25.254.20

;; Query time: 1 msec
;; SERVER: 172.25.254.100#53(172.25.254.100)
;; WHEN: Sun Feb 08 23:13:06 CST 2026
;; MSG SIZE  rcvd: 85

[root@windows ~]# 

FastCGI

CGI 的由来:
最早的 Web 服务器只能简单地响应浏览器发来的 HTTP 请求,并将存储在服务器上的 HTML 文件返回给浏览器,也就是静态HTML 文件,但是后期随着网站功能增多网站开发也越来越复杂,以至于出现动态技 术,比如像php(1995 年 ) 、 Java(1995) 、 Python(1991) 语言开发的网站,但是 nginx/apache 服务器并不 能直接运行 php 、 Java 这样的文件, apache 实现的方式是打补丁,但是 nginx 缺通过与第三方基于协议实现,即通过某种特定协议将客户端请求转发给第三方服务处理,第三方服务器会新建新的进程处理用户的请求,处理完成后返回数据给Nginx 并回收进程,最后 nginx 在返回给客户端,那这个约定就是通用网关接口(common gateway interface ,简称 CGI) , CGI (协议) 是 web 服务器和外部应用程序之间的接口标准,是cgi 程序和 web 服务器之间传递信息的标准化接口


为什么会有 FastCGI ?
CGI 协议虽然解决了语言解析器和 Web Server 之间通讯的问题,但是它的效率很低,因为 Web Server 每收到一个请求都会创建一个CGI 进程, PHP 解析器都会解析 php.ini 文件,初始化环境,请求结束的时候 再关闭进程,对于每一个创建的CGI 进程都会执行这些操作,所以效率很低,而 FastCGI 是用来提高 CGI 性能的,FastCGI 每次处理完请求之后不会关闭掉进程,而是保留这个进程,使这个进程可以处理多个请求。这样的话每个请求都不用再重新创建一个进程了,大大提升了处理效率。(cgi在php...完成后会关闭进程,新的请求又在打开浪费资源,fastcgi不会)
什么是 PHP-FPM ?
PHP-FPM(FastCGI Process Manager :(FastCGI进程管理器 ) 是一个实现了 Fastcgi 的程序,并且提供进程管理的功能。
进程包括 master 进程和 worker 进程。 master 进程只有一个,负责监听端口,接受来自 web server
的请求
worker 进程一般会有多个,每个进程中会嵌入一个 PHP 解析器,进行 PHP 代码的处理。

FastCGI****配置指令

bash 复制代码
fastcgi_pass address:port;
#转发请求到后端服务器,address为后端的fastcgi server的地址,可用位置:location, if in
location
fastcgi_index name;
#fastcgi默认的主页资源,示例:fastcgi_index index.php;
fastcgi_param parameter value [if_not_empty];
#设置传递给FastCGI服务器的参数值,可以是文本,变量或组合,可用于将Nginx的内置变量赋值给自定义
key
fastcgi_param REMOTE_ADDR $remote_addr; #客户端源IP
fastcgi_param REMOTE_PORT $remote_port; #客户端源端口
fastcgi_param SERVER_ADDR $server_addr; #请求的服务器IP地址
fastcgi_param SERVER_PORT $server_port; #请求的服务器端口
fastcgi_param SERVER_NAME $server_name; #请求的server name
Nginx默认配置示例:
location ~ \.php$ {
root /scripts;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; #默认脚本路径
#fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params; #此文件默认系统已提供,存放的相对路径为prefix/conf
#装的不是默认的rpm应为include fastcgi.com;
}

PHP的源码编译

1.下载源码包

bash 复制代码
[root@Nginx ~]# wget https://www.php.net/distributions/php-8.3.30.tar.gz
[root@Nginx ~]# wget https://mirrors.aliyun.com/rockylinux/9.7/devel/x86_64/os/Packages/o/oniguruma-devel-6.9.6-1.el9.6.x86_64.rpm     #依赖

2.解压

bash 复制代码
[root@Nginx ~]# tar zxf php-8.3.30.tar.gz
[root@Nginx ~]# ls
anaconda-ks.cfg                lee.png              nginx-1.29.4.tar.gz  test.c
daolian.png                    nginx-1.28.1         php-8.3.30
echo-nginx-module-0.64         nginx-1.28.1.tar.gz  php-8.3.30.tar.gz
echo-nginx-module-0.64.tar.gz  nginx-1.29.4         test
[root@Nginx ~]# cd php-8.3.30

3.源码编译

bash 复制代码
[root@Nginx ~]# dnf install gcc systemd-devel-252-51.el9.x86_64 libxml2-devel.x86_64 sqlite-devel.x86_64  libcurl-devel.x86_64  libpng-devel.x86_64 oniguruma-devel-6.9.6-1.el9.6.x86_64.rpm -y

[root@Nginx ~]# cd php-8.3.30/
[root@Nginx php-8.3.30]# ./configure \
--prefix=/usr/local/php \		#安装路径
--with-config-file-path=/usr/local/php/etc \	#指定配置路径
--enable-fpm  \			#用cgi方式启动程序
--with-fpm-user=nginx \	#指定运行用户身份
--with-fpm-group=nginx \
--with-curl \			#打开curl浏览器支持
--with-iconv \			#启用iconv函数,转换字符编码
--with-mhash \			#mhash加密方式扩展库
--with-zlib \			#支持zlib库,用于压缩http压缩传输
--with-openssl \		#支持ssl加密
--enable-mysqlnd \		#mysql数据库
--with-mysqli \			
--with-pdo-mysql \
--disable-debug \		#关闭debug功能
--enable-sockets \		#支持套接字访问
--enable-soap \			#支持soap扩展协议
--enable-xml \			#支持xml
--enable-ftp \			#支持ftp
--enable-gd \			#支持gd库
--enable-exif \			#支持图片元数据
--enable-mbstring \		#支持多字节字符串	
--enable-bcmath \		#打开图片大小调整,用到zabbix监控的时候用到了这个模块
--with-fpm-systemd		#支持systemctl 管理cgi

[root@Nginx php-8.3.30]# make && make install

4.配置PHP

bash 复制代码
[root@Nginx php-8.3.30]# cd /usr/local/php/etc
[root@Nginx etc]# cp -p php-fpm.conf.default  php-fpm.conf

[root@Nginx etc]# vim php-fpm.conf
[global]
; Pid file
; Note: the default prefix is /usr/local/php/var
; Default Value: none
pid = run/php-fpm.pid


[root@Nginx etc]# cd php-fpm.d/
[root@Nginx php-fpm.d]# cp www.conf.default www.conf
[root@Nginx php-fpm.d]# vim www.conf
41 listen = 0.0.0.0:9000

[root@Nginx php-fpm.d]# cp /root/php-8.3.30/php.ini-production  /usr/local/php/etc/php.ini

[root@Nginx php-fpm.d]# vim /usr/local/php/etc/php.ini
989 date.timezone = Asia/Shangha

[root@Nginx ~]# cp /root/php-8.3.30/sapi/fpm/php-fpm.service /lib/systemd/system/
[root@Nginx ~]# vim /lib/systemd/system/php-fpm.service

# Mounts the /usr, /boot, and /etc directories read-only for processes invoked by this unit.
#ProtectSystem=full		#注释此参数
[root@Nginx ~]# systemctl daemon-reload
[root@Nginx ~]# systemctl enable --now php-fpm

[root@Nginx ~]# netstat -antlupe | grep php
tcp        0      0 0.0.0.0:9000            0.0.0.0:*               LISTEN      0          329917     165562/php-fpm: mas

5.为php设定环境变量

bash 复制代码
[root@Nginx ~]# vim ~/.bash_profile
export PATH=$PATH:/usr/local/nginx/sbin:/usr/local/php/sbin:/usr/local/php/bin

[root@Nginx ~]# source   ~/.bash_profile
[root@Nginx ~]# php -m

Nginx整合PHP

bash 复制代码
[root@Nginx conf.d]# mkdir  /webdir/timinglee.org/php/html -p
[root@Nginx conf.d]# vim /webdir/timinglee.org/php/html/index.html
php.timinglee.org
#我的
[root@nginx conf.d]# echo php.xier.org > /webdir/xier.org/php/html/index.html


[root@Nginx conf.d]# vim /webdir/timinglee.org/php/html/index.php
<?php
  phpinfo();
?>


[root@Nginx ~]# cd /usr/local/nginx/conf/conf.d/
[root@Nginx conf.d]# vim php.conf
server {
  listen 80;
  server_name php.timinglee.org;
  root /webdir/timinglee.org/php/html;
  location ~ \.php$ {
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    include fastcgi.conf;
  }
}

# location :Nginx指令,用于定义URL路径的处理规则
# ~ :正则表达式匹配标志,表示后面的模式是一个正则表达式
# \.php$ :正则表达式,匹配以 .php 结尾的URL路径
# \. :转义的点号,匹配实际的点字符
# php :匹配字面量"php"
# $ :匹配字符串结尾
[root@Nginx conf.d]# nginx -s reload

#测试
http://php.timinglee.org

http://php.timinglee.org/index.php

注意:测试前确保域名的解析在hosts文件中

利用memcache实现php的缓存加速

原理

客户访问nginx,nginx通过fpm给php,php处理完放到Memached内存中下次在用直接内存中取实现加速,速度取决于php

1.安装memcache

复制代码
dnf install memcached.x86_64 -y

2.配置memcache

bash 复制代码
[root@Nginx ~]# vim /etc/sysconfig/memcached
PORT="11211"
USER="memcached"
MAXCONN="1024"
CACHESIZE="64"
OPTIONS="-l 0.0.0.0,::1"
​
[root@Nginx ~]# systemctl enable --now memcached.service
​
[root@Nginx ~]# netstat -antlupe | grep memcache
tcp        0      0 0.0.0.0:11211           0.0.0.0:*               LISTEN      991        437305     166169/memcached
tcp6       0      0 ::1:11211               :::*                    LISTEN      991        437306     166169/memcached
​

由127.0.0.1改成0.0.0.0将本地访问模式 切换到 网络访问模式,

127.0.0.1 (回环地址)

  • 定义 :本地回环地址,仅允许本机内部访问

  • 作用 :限制服务只在服务器内部可访问,外部网络无法连接

  • 安全性 :高,因为完全隔离外部访问

0.0.0.0 (通配地址)

  • 定义 :IPv4 通配地址,表示监听所有可用的网络接口

  • 作用 :允许从任何网络接口(包括本地和外部网络)访问服务

  • 安全性 :较低,因为开放了外部访问权限

3.升级php对于memcache的支持

bash 复制代码
[root@Nginx ~]# php -m  | grep memcache #查看php支持的插件
​
[root@Nginx ~]# tar zxf memcache-8.2.tgz
[root@Nginx ~]# cd memcache-8.2/
[root@Nginx memcache-8.2]# dnf install autoconf -y
[root@Nginx memcache-8.2]# phpize
[root@Nginx memcache-8.2]# ./configure  && make && make install
​
[root@Nginx memcache-8.2]# ls /usr/local/php/lib/php/extensions/no-debug-non-zts-20230831/
memcache.so  opcache.so
​
[root@Nginx memcache-8.2]# vim /usr/local/php/etc/php.ini
939  extension=memcache
#添加
​
[root@Nginx memcache-8.2]# systemctl restart php-fpm.service
[root@Nginx memcache-8.2]# php -m  | grep memcache
memcache

4.测试性能

bash 复制代码
[root@Nginx memcache-8.2]# vim memcache.php
define('ADMIN_USERNAME','admin');   // Admin Username
define('ADMIN_PASSWORD','lee');     // Admin Password
...
$MEMCACHE_SERVERS[] = '172.25.254.100:11211'; // add more as an array
#$MEMCACHE_SERVERS[] = 'mymemcache-server2:11211'; // add more as an array
​
[root@Nginx memcache-8.2]# cp -p memcache.php  /webdir/timinglee.org/php/html/
[root@Nginx memcache-8.2]# cp -p example.php /webdir/timinglee.org/php/html/
​
#测试
http://php.xier.org/memcache.php           #数据页面,在浏览器中可以直接访问
#因为还是依赖php去取缓存所有高并发还是回有很多失败

[root@Nginx memcache-8.2]# ab -n 1000 -c 300  php.xier.org/example.php
​
复制代码
ab 后看命中是否接近100%

​

nginx+memcache实现高速缓存解

1.重新编译nginx

1)删除旧nginx

bash 复制代码
[root@nginx memcache-8.2]# systemctl stop nginx.service 
[root@nginx memcache-8.2]# cp /usr/local/nginx/conf/ /mnt/ -r
[root@nginx memcache-8.2]# rm -fr /usr/local/nginx/
[root@nginx memcache-8.2]# cd ~
[root@nginx ~]# ll
总用量 22640
-rw-r--r--   1 root root       652  2月  3 14:56 1
-rw-r--r--   1 root root    312531  2月  4 08:40 A2E42F5F3B2605A355A194D4973D1065.jpg
-rw-------.  1 root root      1000  1月 14 18:32 anaconda-ks.cfg
drwxrwxr-x   5 root root       174 10月 30 15:40 echo-nginx-module-0.64
-rw-r--r--   1 root root     53549  2月  1 22:03 echo-nginx-module-0.64.tar.gz
drwxr-xr-x  10 root root      4096  2月  6 17:59 memcache-8.2
-rw-r--r--   1 root root     78413  2月  6 15:15 memcache-8.2.tgz
drwxr-xr-x   9  502 games     4096  2月  1 22:05 nginx-1.28.1
-rw-r--r--   1 root root   1282057 12月 24 02:45 nginx-1.28.1.tar.gz
drwxr-xr-x   9  502 games     4096  1月 31 10:40 nginx-1.29.4
-rw-r--r--   1 root root   1309500 12月 10 02:32 nginx-1.29.4.tar.gz
-rw-r--r--   1 root root     66719 11月  5  2024 oniguruma-devel-6.9.6-1.el9.6.x86_64.rpm
-rw-r--r--   1  501 games    31955  4月 30  2023 package.xml
drwxrwxr-x  21 root root      4096  2月  4 11:37 php-8.3.30
-rw-r--r--   1 root root  20003759  1月 14 06:50 php-8.3.30.tar.gz
[root@nginx ~]# rm -rf nginx-1.29.4 nginx-1.28.1
[root@nginx ~]# 

2)重新编译

bash 复制代码
[root@nginx ~]# tar zxf nginx-1.28.1.tar.gz 
[root@nginx ~]# tar zxf srcache-nginx-module-0.33.tar.gz #自备安装包
[root@nginx ~]# tar zxf memc-nginx-module-0.20.tar.gz #自备安装包
[root@nginx ~]# cd nginx-1.28.1/
[root@nginx nginx-1.28.1]# ./configure  --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module --add-module=/root/echo-nginx-module-0.64  --add-module=/root/memc-nginx-module-0.20 --add-module=/root/srcache-nginx-module-0.33
[root@Nginx nginx-1.28.1]# make && make install
[root@nginx nginx-1.28.1]# cd /usr/local/nginx/conf/
[root@nginx conf]# rm -rf nginx.conf
-r 表 递归(recursive),. 表 当前工作目录, cp基本语法: cp [选项] 源文件 目标位置
[root@nginx conf]# cp -r /mnt/conf/nginx.conf /mnt/conf/conf.d/ .
[root@nginx conf]# systemctl start nginx.service 
[root@nginx conf]# 

2.整合memcache

bash 复制代码
[root@nginx conf]# 
[root@nginx conf]# vim /usr/local/nginx/conf/conf.d/php.conf 
 upstream memcache { 
//定义名为memcache的上游服务器用于负载均衡和连接管理,将请求转发到后端的memcached服务器
   1     server 127.0.0.1:11211;
//指定memcached服务器地址为本地回环端口为11211
   2     keepalive 512;
//可以保持512个长连接到memcached服务器,避免频繁建立断开连接提高性能
   3 }
   4 server {
   5     listen 80;
   6     server_name php.xier.org;
   7     root /webdir/xier.org/php/html;
   8     index index.php index.html;
//设置默认索引文件
   9 
//memcached缓存位置配置
  10     location /memc {
//定义URL路径为/memc的location块,处理与memcached的交互
  11         internal;
//设为内部位置,只能nginx从内部调用,防止绕过安全机制直接缓存
  12         memc_connect_timeout 100ms;
  13         memc_send_timeout 100ms;
  14         memc_read_timeout 100ms;
//设置超时时间,超时则直接走php
  15         set $memc_key $query_string;
//memached采用键值对储存,内置变量$query_string请求名做为键值
//$query_string 存储客户端请求中 ? 后面的所有内容
//访问: http://php.timinglee.org/index.php?id=123&name=test&page=5
//$query_string id=123&name=test&page=5 
//$args id=123&name=test&page=5
//例如: ?id=123&name=test 会作为缓存的键
  16         set $memc_exptime 300;
//设置缓存超时时间300秒5分钟
  17         memc_pass memcache;
//- 将请求传递给之前定义的 memcache 上游服务器组就是转发到 127.0.0.1:11211 的 memcached
 18         }
  19 
  20     location ~ \.php$ {
  21         set $key $uri$args;
//$uri 是一个 内置变量 ,表示当前请求的 URI(统一资源标识符)
//假设用户访问: http://php.timinglee.org/index.php?id=123&name=test
//$uri = /index.php
//$args = id=12
//$key = /index.phpid=123
//   $args;
//存放了URL中的所有参数
//如:https://search.df.com/search?keyword=sadas&enc=utf-8
//$args=keyword=sadas&enc=utf-8

  22         srcache_fetch GET /memc $key;
//- GET 方法访问内部 location /memc
// 如果缓存命中,直接返回缓存内容,不再执行 PHP 如果缓存未命中,继续执行后续的 PHP 处理
  23         srcache_store PUT /memc $key;
//- 将 PHP 执行结果存入缓存
//使用 PUT 方法访问内部 location /memc
//PHP 执行完成后,将响应内容存储到 memcached 下次相同请求可以直接从缓存读取
  24         fastcgi_pass 127.0.0.1:9000;
//- 将 PHP 请求转发到 FastCGI 服务器 地址为 127.0.0.1:9000(通常是 PHP-FPM 监听的端口)
  25         fastcgi_index index.php;
//设置 FastCGI 的默认索引文件为 index.php
  26         include fastcgi.conf;
//包含 FastCGI 的标准配置文件
  27         }

纯代码

bash 复制代码
upstream memcache {
    server 127.0.0.1:11211;
    keepalive 512;
}
server {
    listen 80;
    server_name php.xier.org;
    root /webdir/xier.org/php/html;
    index index.php index.html;

    location /memc {
        internal;
        memc_connect_timeout 100ms;
        memc_send_timeout 100ms;
        memc_read_timeout 100ms;
        set $memc_key $query_string;
        set $memc_exptime 300; 
        memc_pass memcache;
        }    

    location ~ \.php$ {
        set $key $uri$args; 
        srcache_fetch GET /memc $key;
        srcache_store PUT /memc $key;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        include fastcgi.conf;
        } 

测试

bash 复制代码
[root@windows ~]# ab -n 10000 -c 500 php.xier.org/index.php
···
Concurrency Level:      500
Time taken for tests:   14.723 seconds
Complete requests:      10000
Failed requests:        6
···

nginx 二次开发版本 OpenResty

官网: http://openresty.org/cn/

编译安装 openresty

重新克隆一台虚拟机,openresty就是nginx,在有nginx的服务器启动不了

https://openresty.org/download/openresty-1.27.1.2.tar.gz

bash 复制代码
[root@nginx ~]# wget https://openresty.org/download/openresty-1.27.1.2.tar.gz
[root@nginx ~]# dnf install gcc pcre-devel perl zlib-devel -y
[root@nginx ~]# useradd -r -s /sbin/nologin nginx
//-r 创建系统用户 -s 指定用户登录的shell /sbin/nologin一个特殊的shell,一个阻止用户登录的shell
//
[root@nginx ~]# tar zxf openresty-1.27.1.2.tar.gz 
[root@nginx ~]# cd openresty-1.27.1.2/

[root@open openresty-1.27.1.2]# ./configure --prefix=/usr/local/openresty --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module


[root@nginx openresty-1.27.1.2]# gmake && gmake install 

[root@nginx ~]# vim ~/.bash_profile 
···
9    export PATH=$PATH:/usr/local/openresty/bin
//在$PATH:后添加openresty的安装路径即可,即--prefix= 后的内容

[root@nginx ~]# source ~/.bash_profile 

测试

bash 复制代码
[root@open ~]# openresty 
[root@open ~]# openresty -v
nginx version: openresty/1.27.1.2
[root@open ~]# ps -ef | grep nginx
root       50995       1  0 20:55 ?        00:00:00 nginx: master process openresty
nginx      50996   50995  0 20:55 ?        00:00:00 nginx: worker process
root       51043   49941  0 21:01 pts/1    00:00:00 grep --color=auto nginx
[root@open ~]# echo xierxier > /usr/local/openresty/nginx/html/index.html
[root@open ~]# curl 172.25.254.200
xierxier
[root@open ~]# 
相关推荐
wefg12 小时前
【Linux】进程地址空间的内核空间
linux·运维·服务器
GISer_Jing2 小时前
Taro全栈学习路线与实战指南:从基础语法到工程化、性能优化深度进阶
前端·react.js·taro
不知名。。。。。。。。2 小时前
Linux网络基础
运维·服务器·网络
zh_xuan2 小时前
React Native Demo
android·javascript·react native·ts
两个西柚呀2 小时前
每日前端面试题-如何判断空对象,如何区分数据类型
前端
一只理智恩2 小时前
基于 CesiumJS + React + Go 实现三维无人机编队实时巡航可视化系统
前端·人工智能·算法·golang·无人机
henry1010102 小时前
DeepSeek生成的HTML5小游戏 -- 投篮小能手
前端·javascript·css·游戏·html5
Zhu_S W2 小时前
EasyExcel:让Excel操作变得简单优雅
java·前端
GISer_Jing2 小时前
从零到架构师:Taro 全链路学习与实战指南
前端·react.js·taro