Nginx

简介

Nginx是由1994年毕业于俄罗斯国立莫斯科鲍曼科技大学的同学 伊戈尔**·****赛索耶夫**为俄罗斯著名搜索网站rambler.ru开发的,开发工作最早从2002年开始,第一次公开发布时间是2004年10月4日,版本号是 0.1.0
2019年3月11日F5 与 NGINX达成协议,F5 将收购 NGINX 的所有已发行股票,总价值约为 6.7 亿美元6.7亿美金约合44.97亿人民币,nginx核心模块代码长度198430(包括空格、注释),所以一行代码约为2.2万人民币
官网地址 www.nginx.org
Nginx历经十几年的迭代更新(https://nginx.org/en/CHANGES), 目前功能已经非常完善且运行稳 定,另外Nginx的版本分为开发版、稳定版和过期版,nginx以功能丰富著称,它即可以作为http服务 器,也可以作为反向代理服务器或者邮件服务器能够快速的响应静态网页的请求
支持FastCGI/SSL/Virtual Host/URL Rwrite /Gzip / HTTP Basic Auth/http或者TCP的负载均衡(1.9版本以 上且开启stream模块)等功能,并且支持第三方的功能扩展。
天猫 淘宝 京东 小米 163 新浪等一线互联网公司都在用Nginx或者进行二次开发基于Nginx的工作场景:

Nginx****功能介绍

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

基础特性

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

Web****服务相关的功能

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

Nginx****架构和进程


web请求处理机制

  • 多进程方式:服务器每接收到一个客户端请求就有服务器的主进程生成一个子进程响应客户端,直到用户关闭连接,这样的优势是处理速度快,子进程之间相互独立,但是如果访问过大会导致服务器资源耗尽而无法提供请求。
  • 多线程方式:与多进程方式类似,但是每收到一个客户端请求会有服务进程派生出一个线程和此客户端进行交互,一个线程的开销远远小于一个进程,因此多线程方式在很大程度减轻了web服务器对系统资源的要求,但是多线程也有自己的缺点,即当多个线程位于同一个进程内工作的时候,可以相互访问同样的内存地址空间,所以他们相互影响,一旦主进程挂掉则所有子线程都不能工作了,IIS服务器使用了多线程的方式,需要间隔一段时间就重启一次才能稳定。

Nginx是多进程组织模型,而且是一个由Master主进程和Worker工作进程组成


主进程(master process)的功能:

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

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

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

Nginx启动和HTTP****连接建立

  • Nginx 启动时,Master 进程,加载配置文件
  • Master 进程,初始化监听的 socket
  • Master 进程,fork 出多个 Worker 进程
  • Worker 进程,竞争新的连接,获胜方通过三次握手,建立 Socket 连接,并处理请求

Nginx****模块介绍

nginx 有多种模块

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

Nginx的源码编译

#下载软件:

[root@Nginx ~]# wget https://nginx.org/download/nginx-1.28.1.tar.gz

#解压

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 #环境监测 #安装依赖性 \[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 \\ # 指定nginx运行用户 --group=nginx \\ # 指定nginx运行组 --with-http_ssl_module \\ # 支持https:// --with-http_v2_module \\ # 支持http版本2 --with-http_realip_module \\ # 支持ip透传 --with-http_stub_status_module \\ # 支持状态页面 --with-http_gzip_static_module \\ # 支持压缩 --with-pcre \\ # 支持正则 --with-stream \\ # 支持tcp反向代理 --with-stream_ssl_module \\ # 支持tcp的ssl加密 --with-stream_realip_module # 支持tcp的透传ip #编译 \[root@Nginx nginx-1.28.1\]# make \[root@Nginx nginx-1.28.1\]# make install \[root@Nginx nginx-1.28.1\]# ls /usr/local/nginx/ conf html logs sbin #conf:保存nginx所有的配置文件,其中nginx.conf是nginx服务器的最核心最主要的配置文件,其他 的.conf则是用来配置nginx相关的功能的,例如fastcgi功能使用的是fastcgi.conf和 fastcgi_params两个文件,配置文件一般都有一个样板配置文件,是以.default为后缀,使用时可将其 复制并将default后缀去掉即可。 #html目录中保存了nginx服务器的web文件,但是可以更改为其他目录保存web文件,另外还有一个50x的 web文件是默认的错误页面提示页面。 l#ogs:用来保存nginx服务器的访问日志错误日志等日志,logs目录可以放在其他路径,比 如/var/logs/nginx里面。 #sbin:保存nginx二进制启动脚本,可以接受不同的参数以实现不同的功能。 #启动 #设定环境变量 \[root@Nginx sbin\]# vim \~/.bash_profile export PATH=$PATH:/usr/local/nginx/sbin \[root@Nginx sbin\]# source \~/.bash_profile \[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 hjw \> /usr/local/nginx/html/index.html \[root@Nginx logs\]# curl 172.25.254.100 hjw #编写启动文件 \[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的平滑升级及回滚

  • 将旧Nginx二进制文件换成新Nginx程序文件(注意先备份)
  • 向master进程发送USR2信号
  • master进程修改pid文件名加上后缀.oldbin,成为nginx.pid.oldbin
  • master进程用新Nginx文件启动新master进程成为旧master的子进程,系统中将有新旧两个Nginx主进程共同提供Web服务,当前新的请求仍然由旧Nginx的worker进程进行处理,将新生成的master进程的PID存放至新生成的pid文件nginx.pid
  • 向旧的Nginx服务进程发送WINCH信号,使旧的Nginx worker进程平滑停止
  • 向旧master进程发送QUIT信号,关闭老master,并删除Nginx.pid.oldbin文件
  • 如果发现升级有问题,可以回滚∶向老master发送HUP,向新master发送QUIT

#下载高版本软件

root@Nginx \~\]# wget https://nginx.org/download/nginx-1.29.4.tar.gz #对于新版本的软件进行源码编译并进行平滑升级 #编译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 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 nginx \[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 #USR2 平滑升级可执行程序,将存储有旧版本主进程PID的文件重命名为nginx.pid.oldbin,并启动新的 nginx #此时两个master的进程都在运行,只是旧的master不在监听,由新的master监听80 #此时Nginx开启一个新的master进程,这个master进程会生成新的worker进程,这就是升级后的Nginx进程,此时老的进程不会自动退出,但是当接收到新的请求不作处理而是交给新的进程处理。 \[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

版本回退|版本回滚

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配置文件的管理及优化参数

配置文件详解

复制代码
#全局配置端,对全局生效,主要设置nginx的启动用户/组,启动的工作进程数量,工作模式,Nginx的PID
路径,日志路径等。
user nginx nginx;
worker_processes 1; #启动工作进程数数量
events { 
            #events #设置快,主要影响nginx服务器与用户的网络连接,比如是否允许同时接受多个网络连接,使用哪种事件驱动模型 #处理请求,每个工作进程可以同时支持的最大连接数,是否开启对多工作进程下的网络连接进行序列化等。
            worker_connections 1024; #设置单个nginx工作进程可以接受的最大并发,作为web服务器的时候最大并发数为 #worker_connections* worker_processes,作为反向代理的时候为
                                        #(worker_connections * worker_processes)/2
        }
http { 
            #http块是Nginx服务器配置中的重要部分,缓存、代理和日志格式定义等绝大多数功能和第三方模块都 #可以在这设置,http块可以包含多个server块,而一个server块中又可以包含多个location块,
            #server块可以配置文件引入、MIME-Type定义、日志自定义、是否启用sendfile、连接超时时间和 #单个链接的请求上限等。
    include mime.types;
    default_type application/octet-stream;
    sendfile on;         #作为web服务器的时候打开sendfile加快静态文件传输,指定是否使用
                         #sendfile系统调用来传输文件
                         #sendfile系统调用在两个文件描述符之间直接传递数据(完全在内核中操作)
                         #从而避免了数据在内核缓冲区和用户缓冲区之间的拷贝,操作效率很高,被称之为零拷贝,
                         #硬盘 >> kernel buffer (快速拷贝到kernelsocketbuffer) >>协议栈。
keepalive_timeout 65; #长连接超时时间,单位是秒
server { 
                #设置一个虚拟机主机,可以包含自己的全局快,同时也可以包含多个location模块
                #比如本虚拟机监听的端口、本虚拟机的名称和IP配置,多个server 可以使用一个端口比如都使用 #80端口提供web服务
        listen 80; #配置server监听的端口
        server_name localhost; #本server的名称,当访问此名称的时候nginx会调用当前serevr内部的配置进程匹配。
        location / { #location其实是server的一个指令,为nginx服务器提供比较多而且灵活的指令
                #都是在location中体现的,主要是基于nginx接受到的请求字符串
                #对用户请求的UIL进行匹配,并对特定的指令进行处理
                #包括地址重定向、数据缓存和应答控制等功能都是在这部分实现
                #另外很多第三方模块的配置也是在location模块中配置。
        root html; #相当于默认页面的目录名称,默认是安装目录的相对路径,可以使用绝对路径配置。
        index index.html index.htm; #默认的页面文件名称
            }
        error_page 500 502 503 504 /50x.html; #错误页面的文件名称
        location = /50x.html { #location处理对应的不同错误码的页面定义到/50x.html
                #这个跟对应其server中定义的目录下。
        root html; #定义默认页面所在的目录
        }
    }

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

如:修改用户 进程数

root@Nginx \~\]# vim /usr/local/nginx/conf/nginx.conf user nginx; \[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 \[root@Nginx \~\]# vim /usr/local/nginx/conf/nginx.conf worker_processes 2; \[root@Nginx \~\]# nginx -s reload \[root@Ngix \~\]# ps -aux \| grep nginx root 3971 0.0 0.0 10064 936 ? Ss 15:20 0:00 nginx: master process /usr/local/nginx/sbin/nginx nginx 3972 0.1 0.5 17544 9676 ? S 15:20 0:00 nginx: worker process nginx 3973 0.0 0.5 17404 9652 ? S 15:20 0:00 nginx: worker process nginx 3974 0.0 0.5 17396 9644 ? S 15:20 0:00 nginx: worker process nginx 3975 0.0 0.5 17396 9644 ? S 15:20 0:00 nginx: worker process root 4024 0.0 0.5 14632 9380 pts/0 S+ 15:20 0:00 vim /usr/local/nginx/conf/nginx.conf root 6396 0.0 0.1 6636 2212 pts/1 S+ 15:26 0:00 grep --color=auto nginx

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

root@Nginx \~\]# vim /usr/local/nginx/conf/nginx.conf worker_processes auto; worker_cpu_affinity 0001 0010 0100 1000; #测试 \[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 \[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 \[root@Nginx \~\]# vim /usr/local/nginx/conf/nginx.conf events { worker_connections 10000; use epoll; accept_mutex on; multi_accept on; } \[root@Nginx \~\]# nginx -s reload #测试并发 \[root@Nginx \~\]# dnf install httpd-tools -y \[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) #并发数量过多导致访问失败 #处理本地文件系统的并发文件数量 \[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

Nginx下构建PC站点

location中的root

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 /web/nginx/hjw.org/lee/html \[root@Nginx \~\]# echo lee.hjw.org \> /web/nginx/hjw.org/lee/html/index.html \[root@Nginx conf.d\]# vim vhosts.conf server { listen 80; server_name lee.hjw.org; location / { root /web/nginx/hjw.org/lee/html; } } root@Nginx conf.d\]# systemctl restart nginx.service #测试 \[root@Nginx conf.d\]# vim /etc/hosts 172.25.254.100 Nginx www.hjw.org lee.hjw.org \[root@Nginx conf.d\]# curl www.hjw.org hjw \[root@Nginx conf.d\]# curl lee.hjw.org lee.hjw.org #local示例需要访问lee.hjw.org/lee/目录 \[root@Nginx conf.d\]# vim vhosts.conf server { listen 80; server_name lee.hjw.org; location / { root /web/nginx/hjw.org/lee/html; } location /lee { #lee标识location中的root值+location 后面指定的值代表目录的路径 root /web/nginx/hjw.org/lee/html; } } \[root@Nginx conf.d\]# systemctl restart nginx.service \[root@Nginx conf.d\]# mkdir -p /web/nginx/hjw.org/lee/html/lee \[root@Nginx conf.d\]# echo lee \> /web/nginx/hjw.org/lee/html/lee/index.html \[root@Nginx conf.d\]# curl lee.hjw.org/lee/ lee

location中的alias

root@Nginx conf.d\]# vim vhosts.conf server { listen 80; server_name lee.hjw2.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.hjw2.org/passwd/ passwd \[root@Nginx conf.d\]# curl lee.hjw2.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

KeepAlived长链接优化

设定长链接时间

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.hjw.org 80 Trying 172.25.254.100... Connected to www.hjw.org. Escape character is '\^\]'. GET / HTTP/1.1 \<\<\<\< Host: www.hjw.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 hjw 显示的页面出现后根据设定的长链接时间会等待,超过时间后会自动退出 Connection closed by foreign host.

设定长链接次数

root@Nginx \~\]# vim /usr/local/nginx/conf/nginx.conf #keepalive_timeout 0; keepalive_timeout 120; keepalive_requests 2; \[root@Nginx \~\]# nginx -s reload #测试 \[root@Ngix \~\]# telnet www.hjw.org 80 Trying 172.25.254.100... Connected to www.hjw.org. Escape character is '\^\]'. GET / HTTP/1.1 Host: www.hjw.org HTTP/1.1 200 OK Server: nginx/1.28.1 Date: Sat, 31 Jan 2026 08:49:26 GMT Content-Type: text/html Content-Length: 4 Last-Modified: Sat, 31 Jan 2026 06:51:39 GMT Connection: keep-alive ETag: "697da67b-4" Accept-Ranges: bytes hjw GET / HTTP/1.1 Host: www.hjw.org HTTP/1.1 200 OK Server: nginx/1.28.1 Date: Sat, 31 Jan 2026 08:49:37 GMT Content-Type: text/html Content-Length: 4 Last-Modified: Sat, 31 Jan 2026 06:51:39 GMT Connection: close ETag: "697da67b-4" Accept-Ranges: bytes hjw Connection closed by foreign host.

location参数详解

root@Ngix conf.d\]# cat vhosts.conf server { listen 80; server_name lee.hjw.org; location /null { return 200 "/null-1";普通前缀匹配 } location = /null { return 200 "/null-2"; 精确匹配 /null - 完全匹配 } location \~ /null { return 200 "/null-3"; 区分大小写的正则匹配 } location \~\* /hjw { return 200 "/hjw-4"; 不区分大小写的正则匹配 } location \~\* \\.(img\|php\|jsp)$ { return 200 "app"; #匹配以.img .php .jsp结尾的 } } \[root@Ngix conf.d\]# curl lee.hjw.org/test.jsp app\[root@Ngix conf.d\]# curl lee.hjw.org/test.img app\[root@Ngix conf.d\]# curl lee.hjw.org/hjw.img /hjw-4\[root@Ngix conf.d\]# curl lee.hjw.org/null /null-2\[root@Ngix conf.d\]# curl lee.hjw.org/null.img /null-3\[root@Ngix conf.d\]# curl lee.hjw.org/null.php /null-3\[root@Ngix conf.d\]# curl lee.hjw.org/testphp \ \\404 Not Found\\ \ \\404 Not Found\\ \\nginx/1.28.1\ \ \ \[root@Ngix conf.d\]# curl lee.hjw.org/test.php app\[root@Ngix conf.d\]# curl lee.hjw.org/Hjw /hjw-4

    1. location = /uri # 精确匹配(最高优先级)
    1. location ^~ /uri # 前缀匹配(停止正则检查)
    1. location ~ 正则 # 区分大小写的正则匹配
    1. location ~* 正则 # 不区分大小写的正则匹配
    1. location /uri # 普通前缀匹配
    1. location / # 通用匹配(最低优先级)

服务访问的用户认证

root@Nginx \~\]# htpasswd -cmb /usr/local/nginx/conf/.htpasswd admin lee Adding password for user admin \[root@Ngix \~\]# mkdir /usr/local/nginx/html/admin -p \[root@Ngix \~\]# echo admin \> /usr/local/nginx/html/admin/index.html \[root@Nginx \~\]# vim /usr/local/nginx/conf/conf.d/vhosts.conf server { listen 80; server_name lee.hjw.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@Ngix conf.d\]# curl lee.hjw.org/admin \ \\401 Authorization Required\\ \ \\401 Authorization Required\\ \\nginx/1.28.1\ \ \ \[root@Ngix conf.d\]# curl -uadmin:hjw lee.hjw.org/admin/ admin \[root@Ngix conf.d\]#

自定义错误页面

root@Nginx \~\]# mkdir /usr/local/nginx/errorpage \[root@Nginx \~\]# echo "太不巧了,hjw放假了!!" \> /usr/local/nginx/errorpage/errormessage \[root@Nginx \~\]# cat /usr/local/nginx/errorpage/errorhjw 太不巧了,hjw放假了!! \[root@Nginx \~\]# vim /usr/local/nginx/conf/conf.d/vhosts.conf server { listen 80; server_name lee.timinglee.org; error_page 404 401 405 503 502 /error; location /lee { root /usr/local/nginx/html; } location /error { alias /usr/local/nginx/errorpage/errorhjw; } } \[root@Ngix conf.d\]# curl lee.hjw.org/admin/ 太不巧了,hjw放假了!!

自定义错误日志

root@Nginx \~\]# mkdir -p /usr/local/nginx/logs/hjw.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/hjw.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/hjw.org/ \[root@Nginx timinglee.org\]# ls lee.error \[root@Nginx timinglee.org\]# cat lee.error \[root@Ngix hjw.org\]# curl lee.hjw.org/lee 太不巧了,hjw放假了!! \[root@Ngix hjw.org\]# cat lee.error 2026/02/22 11:30:33 \[error\] 74965#0: \*2 open() "/usr/local/nginx/html/lee" failed (2: No such file or directory), client: 172.25.254.100, server: lee.hjw.org, request: "GET /lee HTTP/1.1", host: "lee.hjw.org"

Nginx中建立下载服务器

root@Nginx \~\]# mkdir -p /usr/local/nginx/download \[root@Nginx \~\]# cp /etc/passwd /usr/local/nginx/download/ \[root@Nginx \~\]# dd if=/dev/zero of=/usr/local/nginx/download/bigfile bs=1M count=100 记录了100+0 的读入 记录了100+0 的写出 104857600字节(105 MB,100 MiB)已复制,0.152409 s,688 MB/s \[root@Nginx \~\]# vim /usr/local/nginx/conf/conf.d/vhosts.conf server { listen 80; server_name lee.hjw.org; error_page 404 405 503 502 /error; error_log logs/hjw.org/lee.error error; location /lee { root /usr/local/nginx/html; } location /error { alias /usr/local/nginx/errorpage/errorhjw; } location /download { root /usr/local/nginx; } } \[root@Nginx \~\]# nginx -s reload

启用列表功能

root@Nginx \~\]# vim /usr/local/nginx/conf/conf.d/vhosts.conf server { listen 80; server_name lee.hjw.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/errorhjw; } location /download { root /usr/local/nginx; autoindex on; } } \[root@Nginx \~\]# nginx -s reload

下载控速

root@Nginx \~\]# wget http://lee.hjw.org/download/bigfile --2026-02-01 11:37:52-- http://lee.hjw.org/download/bigfile 正在解析主机 lee.hjw.org (lee.timinglee.org)... 172.25.254.100 正在连接 lee.hjw.org (lee.hjw.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.hjw.org; error_page 404 405 503 502 /error; error_log logs/hjw.org/lee.error error; location /lee { root /usr/local/nginx/html; } location /error { alias /usr/local/nginx/errorpage/errorhjw; } location /download { root /usr/local/nginx; autoindex on; limit_rate 1024k; } } \[root@Nginx \~\]# nginx -s reload \[root@Nginx \~\]# wget http://lee.hjw.org/download/bigfile --2026-02-01 11:39:09-- http://lee.hjw.org/download/bigfile 正在解析主机 lee.hjw.org (lee.hjw.org)... 172.25.254.100 正在连接 lee.hjw.org (lee.hjw.org)\|172.25.254.100\|:80... 已连接。 已发出 HTTP 请求,正在等待回应... 200 OK 长度:104857600 (100M) \[application/octet-stream

正在保存至: "bigfile"

bigfile 12%[===> ] 12.00M 1.00MB/s 剩余 88s

显示文件大小优化

root@Nginx \~\]# vim /usr/local/nginx/conf/conf.d/vhosts.conf server { listen 80; server_name lee.hjw.org; error_page 404 405 503 502 /error; error_log logs/hjw.org/lee.error error; location /lee { root /usr/local/nginx/html; } location /error { alias /usr/local/nginx/errorpage/errorhjw; } location /download { root /usr/local/nginx; autoindex on; limit_rate 1024k; autoindex_exact_size off; } } \[root@Nginx \~\]# nginx -s reload

效果

root@Nginx ~]# curl lee.hjw.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.hjw.org/download/ \ \\Index of /download/\\ \ \Index of /download/\\\\../\ \bigfile\ 01-Feb-2026 03:28 100M \passwd\ 01-Feb-2026 03:27 1294 \\\ \

设定页面风格

root@Nginx \~\]# vim /usr/local/nginx/conf/conf.d/vhosts.conf server { listen 80; server_name lee.hjw.org; error_page 404 405 503 502 /error; error_log logs/hjw.org/lee.error error; location /lee { root /usr/local/nginx/html; } location /error { alias /usr/local/nginx/errorpage/errorhjw; } 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

json风格

Nginx的文件检测

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.hjw.org; error_page 404 405 503 502 /error; error_log logs/hjw.org/lee.error error; root /usr/local/nginx/errorpage; try_files $uri $uri.html $uri/index.html /default.html; #添加 location /lee { root /usr/local/nginx/html; } #测试: \[root@Ngix \~\]# curl -v lee.hjw.org/wwww \* Trying 172.25.254.100:80... \* Connected to lee.hjw.org (172.25.254.100) port 80 (#0) \> GET /wwww HTTP/1.1 \> Host: lee.hjw.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:33:56 GMT \< Content-Type: text/html \< Content-Length: 8 \< Last-Modified: Sun, 01 Feb 2026 06:31:54 GMT \< Connection: keep-alive \< ETag: "697ef35a-8" \< Accept-Ranges: bytes \< default \* Connection #0 to host lee.hjw.org left intact

root@Nginx \~\]# vim /usr/local/nginx/conf/conf.d/vhosts.conf server { listen 80; server_name lee.hjw.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的压缩功能

root@Nginx \~\]#mkdir /usr/local/nginx/hjw.org/html -p \[root@Nginx \~\]# echo hello hjw \> /usr/local/nginx/hjw.org/html/index.html \[root@Nginx html\]# cp /usr/local/nginx/logs/access.log /usr/local/nginx/hjw.org/html/bigfile.txt \[root@Nginx \~\]# vim /usr/local/nginx/conf/nginx.conf gzip on; gzip_comp_level 4; gzip_disable "MSIE \[1-6\]\\."; gzip_min_length 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; gzip_buffers 32 1024k; \[root@Nginx \~\]# vim /usr/local/nginx/conf/conf.d/vhosts.conf server { listen 80; server_name lee.hjw.org; root /usr/local/nginx/hjw.org/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@Ngix \~\]# curl --head --compressed lee.hjw.org/bigfile.txt HTTP/1.1 200 OK Server: nginx/1.28.1 Date: Sun, 01 Feb 2026 07:46:14 GMT Content-Type: text/plain Last-Modified: Sun, 01 Feb 2026 07:36:55 GMT Connection: keep-alive Vary: Accept-Encoding ETag: W/"697f0297-9d4f97" Content-Encoding: gzip \[root@Ngix \~\]# curl --head --compressed lee.hjw.org/index.html HTTP/1.1 200 OK Server: nginx/1.28.1 Date: Sun, 01 Feb 2026 07:46:30 GMT Content-Type: text/html Content-Length: 10 Last-Modified: Sun, 01 Feb 2026 07:45:28 GMT Connection: keep-alive ETag: "697f0498-a" Accept-Ranges: bytes

Nginx 变量

  • nginx的变量可以在配置文件中引用,作为功能判断或者日志等场景使用
  • 变量可以分为内置变量和自定义变量
  • 内置变量是由nginx模块自带,通过变量可以获取到众多的与客户端访问相关的值。

常用内置变量

$remote_addr;
#存放了客户端的地址,注意是客户端的公网IP

$args;
#变量中存放了URL中的所有参数
#例如:
https://search.jd.com/Search?keyword=手机\&enc=utf-8
#返回结果为: keyword=手机&enc=utf-8

$is_args
#如果有参数为? 否则为空

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

$document_uri;
#保存了当前请求中不包含参数的URI,注意是不包含请求的指令
#比如:http://lee.timinglee.org/var?\\id=11111会被定义为/var
#返回结果为:/var

$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请求生成的文件绝对路径,
#如:webdata/nginx/timinglee.org/lee/var/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_user_agent;
#客户端浏览器的详细信息

$http_cookie;
#客户端的所有cookie信息

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

http_\ #name为任意请求报文首部字段,表示记录请求报文的首部字段,name的对应的首部字段名需要为小写,如果有横线需要替换为下划线 #示例: echo http_user_agent;
echo $http_host;

$sent_http_<name>
#name为响应报文的首部字段,name的对应的首部字段名需要为小写,如果有横线需要替换为下划线,此变量有问题

echo sent_http_server; arg_<name>
#此变量存放了URL中的指定参数,name为请求url中指定的参数

echo $arg_id;

想要看到变量效果我们要添加模块

升级Nginx支持echo

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

查看变量

root@Nginx nginx-1.28.1\]# vim /usr/local/nginx/conf/conf.d/vhosts.conf listen 80; server_name lee.hjw.org; root /usr/local/nginx/hjw.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; } } \[root@Nginx nginx-1.28.1\]# nginx -s reload \[root@Nginx nginx-1.28.1\]# \[root@Ngix \~\]# curl -b "key1=hello,key2=hjw" -A "haha" -ulee:lee "http://lee.hjw.org/vars?key=lee\&id=11" 172.25.254.100 key=lee\&id=11 ? /usr/local/nginx/hjw.org/html /vars lee.hjw.org 51542 lee GET /usr/local/nginx/hjw.org/html/vars /vars?key=lee\&id=11 http HTTP/1.1 172.25.254.100 lee.hjw.org 80 haha hjw haha \[root@Ngix \~\]#

自定义变量

假如需要自定义变量名称和值,使用指令set variable value; 语法格式: Syntax: set variable value;
Default: ---
Context: server, location, if

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; echo $remote_user; echo $request_method; echo $request_filename; echo $request_uri; echo $scheme; set $test lee; #手动设定变量值 echo $test; set $web_port $server_port; #变量个传递 echo $web_port; } } \[root@Ngix \~\]# curl lee.hjw.org/vars/172.25.254.100 GET /usr/local/nginx/hjw.org/html/vars/172.25.254.100 /vars/172.25.254.100 http lee 80

网页从写

网页重写中的指令

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

root@Nginx \~\]# vim /usr/local/nginx/conf/conf.d/vhosts.conf server { listen 80; server_name lee.hjw.org; root /usr/local/nginx/hjw.org/html; location /vars { echo $remote_user; echo $request_method; echo $request_filename; echo $request_uri; echo $scheme; } location / { if ( $http_user_agent \~\* Chrome ) { return 200 "test if messages"; } } } \[root@Nginx \~\]# nginx -s reload \[root@Nginx \~\]# curl lee.hjw.org hjw \[root@Ngix \~\]# curl -A "Chrome" lee.hjw.org test if messagev #set 指定key并给其定义一个变量,变量可以调用Nginx内置变量赋值给key 另外set定义格式为set $key value,value可以是text, variables和两者的组合。 \[root@Nginx \~\]# vim /usr/local/nginx/conf/conf.d/vhosts.conf server { listen 80; server_name lee.hjw.org; root /usr/local/nginx/hjw.org/html; location /vars { echo $remote_user; echo $request_method; echo $request_filename; echo $request_uri; echo $scheme; } location / { set $testname hjw; echo $testname; } } \[root@Nginx \~\]# nginx -s reload \[root@Nginx \~\]# curl lee.hjw.org hjw #return return用于完成对请求的处理,并直接向客户端返回响应状态码,比如:可以指定重定向URL(对于特殊重 定向状态码,301/302等) 或者是指定提示文本内容(对于特殊状态码403/500等),处于此指令后的所有配 置都将不被执行,return可以在server、if 和 location块进行配置 \[root@Nginx \~\]# vim /usr/local/nginx/conf/conf.d/vhosts.conf server { listen 80; server_name lee.hjw.org; root /usr/local/nginx/hjw.org/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.hjw.org hello world #break 用于中断当前相同作用域(location)中的其他Nginx配置 与该指令处于同一作用域的Nginx配置中,位于它前面的配置生效 位于后面的 ngx_http_rewrite_module 模块中指令就不再执行 Nginx服务器在根据配置处理请求的过程中遇到该指令的时候,回到上一层作用域继续向下读取配置,、 该指令可以在server块和locationif块中使用 **注意: 如果break指令在location块中后续指令还会继续执行,只是不执行 ngx_http_rewrite_module** **模块的指令,其它指令还会执行** \[root@Nginx \~\]# vim /usr/local/nginx/conf/conf.d/vhosts.conf server { listen 80; server_name lee.hjw.org; root /usr/local/nginx/hjw.org/html; location /vars { echo $remote_user; echo $request_method; echo $request_filename; echo $request_uri; echo $scheme; } location / { set $hjw1 hjw1; set $hjw2 hjw2; set $hjw3 hjw3; if ($http_user_agent \~\* Chrome ){ break; set $test1 test1; echo $hjw1 $hjw2 $hjw3 $test1; } } } \[root@Nginx \~\]# nginx -s reload #测试 \[root@Ngix \~\]# curl -A "Chrome" lee.hjw.org hjw1 hjw2 hjw3

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

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

flag****说明
redirect;
#临时重定向,重写完成后以临时重定向方式直接返回重写后生成的新URL给客户端
#由客户端重新发起请求;使用相对路径,或者http://或https://开头,状态码:302
permanent;
#重写完成后以永久重定向方式直接返回重写后生成的新URL给客户端
#由客户端重新发起请求,状态码:301
break;
#重写完成后,停止对当前URL在当前location中后续的其它重写操作
#而后直接跳转至重写规则配置块之后的其它配置,结束循环,建议在location中使用
#适用于一个URL一次重写
last;
#重写完成后,停止对当前URI在当前location中后续的其它重写操作,
#而后对新的URL启动新一轮重写检查,不建议在location中使用
#适用于一个URL多次重写,要注意避免出现超过十次以及URL重写后返回错误的给用户

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

server {
    listen 80;
    server_name lee.hjw.org;
    root /web/hjw.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.hjw.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
[root@Nginx ~]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
​
server {
    listen 80;
    server_name lee.hjw.org;
    root /web/hjw.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.hjw.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 和 last
[root@Ngix ~]# mkdir /web/nginx/hjw.org/lee/html/{break,last,test1,test}
[root@Ngix ~]# ls /web/nginx/hjw.org/lee/html/
break  index.html  last  lee  test  test1
[root@Ngix ~]# cat /web/nginx/hjw.org/lee/html/index.html
lee.hjw.org
[root@Ngix ~]# echo break > /web/nginx/hjw.org/lee/html/break/index.html
[root@Ngix ~]# echo last > /web/nginx/hjw.org/lee/html/last/index.html
[root@Ngix ~]# echo test1 > /web/nginx/hjw.org/lee/html/test1/index.html
[root@Ngix ~]# echo test > /web/nginx/hjw.org/lee/html/test/index.html
​
​
#break
[root@Nginx ~]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
server {
    listen 80;
    server_name lee.hjw.org;
    root  /web/nginx/hjw.org/lee/html/;
    location /break {
        rewrite /break/(.*) /test/$1 braek;
        rewrite /test  /test1;
        rewrite /test1  /last;
    }
    location /test {
        return 200 "test end page";
    }
    location /test1 {
        return 200 "TEST1 END PAGE";
    }
}
​
root@Nginx ~]# nginx -s reload
[root@Ngix ~]# curl  -L  lee.hjw.org/break/index.html
test
​
​
​
#last
[root@Nginx ~]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
server {
    listen 80;
    server_name lee.hjw.org;
    root  /web/nginx/hjw.org/lee/html/;
    location /break {
        rewrite /break/(.*) /test/$1 last;
        rewrite /test  /test1;
        rewrite /test1  /last;
    }
    location /test {
        return 200 "test end page";
    }
    location /test1 {
        return 200 "TEST1 END PAGE";
    }
}
​
root@Nginx ~]# nginx -s reload
[root@Ngix ~]# curl  -L  lee.hjw.org/break/index.html
test end page

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

制作key

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

编辑加密配置文件

root@Nginx \~\]# vim /usr/local/nginx/conf/conf.d/vhosts.conf server { listen 80; listen 443 ssl; ssl_certificate /usr/local/nginx/certs/hjw.org.crt; ssl_certificate_key /usr/local/nginx/certs/hjw.org.key; ssl_session_cache shared:sslcache:20m; ssl_session_timeout 10m; server_name lee.hjw.org; root /web/nginx/hjw.org/lee/html/; location / { if ($scheme = http ){ rewrite /(.\*) https://$host/$1 redirect; } } } \[root@Nginx \~\]# systemctl restart nginx.service \[root@Ngix \~\]# curl -I http://lee.hjw.org/ HTTP/1.1 302 Moved Temporarily Server: nginx/1.28.1 Date: Tue, 03 Feb 2026 03:57:59 GMT Content-Type: text/html Content-Length: 145 Connection: keep-alive Location: https://lee.hjw.org/ \[root@Ngix \~\]# curl -I http://lee.hjw.org/break HTTP/1.1 302 Moved Temporarily Server: nginx/1.28.1 Date: Tue, 03 Feb 2026 03:58:05 GMT Content-Type: text/html Content-Length: 145 Connection: keep-alive Location: https://lee.hjw.org/break


反向代理:reverse proxy,指的是代理外网用户的请求到内部的指定的服务器,并将数据返回给用户的 一种方式,这是用的比较多的一种方式。
Nginx 除了可以在企业提供高性能的web服务之外,另外还可以将 nginx 本身不具备的请求通过某种预定义的协议转发至其它服务器处理,不同的协议就是Nginx服务器与其他服务器进行通信的一种规范,主要在不同的场景使用以下模块实现不同的功能

同构代理:用户不需要其他程序的参与,直接通过http协议或者tcp协议访问后端服务器
异构代理:用户访问的资源时需要经过处理后才能返回的,比如php,Python,等等,这种访问资源需 要经过处理才能被访问

简单的代理方法

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.hjw.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

透传信息

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 #注意\\"%{X-Forwarded-For}i\\" 格式 \[root@RS1 \~\]# systemctl restart httpd \[root@Nginx \~\]# vim /usr/local/nginx/conf/conf.d/vhosts.conf server { listen 80; server_name lee.hjw.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 #测试 C:\\Users\\hjw\>curl -v lee.hjw.org \* Host lee.hjw.org:80 was resolved. \[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"

创建动态数据

#在10中

root@RS1 \~\]# dnf install php -y \[root@RS1 \~\]# systemctl restart httpd \[root@RS1 \~\]# vim /var/www/html/index.php \172.25.254.10\"; phpinfo(); ?\>

动静分离的实现

root@Nginx \~\]# vim /usr/local/nginx/conf/conf.d/vhosts.conf server { listen 80; server_name lee.hjw.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

缓存加速

当未启用缓存时进行压测

root@Yhu \~\]# ab -n 10000 -c 50 lee.hjw.org/index.php This is ApacheBench, Version 2.3 \<$Revision: 1903618 $\> Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ Licensed to The Apache Software Foundation, http://www.apache.org/ Benchmarking lee.hjw.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.hjw.org Server Port: 80 Document Path: /index.php Document Length: 72827 bytes Concurrency Level: 50 Time taken for tests: 6.716 seconds Complete requests: 10000 Failed requests: 9974 (Connect: 0, Receive: 0, Length: 9974, Exceptions: 0) Total transferred: 729927797 bytes HTML transferred: 728297797 bytes Requests per second: 1488.98 \[#/sec\] (mean) Time per request: 33.580 \[ms\] (mean) Time per request: 0.672 \[ms\] (mean, across all concurrent requests) Transfer rate: 106137.25 \[Kbytes/sec\] received Connection Times (ms) min mean\[+/-sd\] median max Connect: 0 2 10.3 1 1026 Processing: 7 32 7.7 31 78 Waiting: 4 26 6.2 25 67 Total: 8 33 12.6 33 1058 Percentage of the requests served within a certain time (ms) 50% 33 66% 36 75% 38 80% 39 90% 43 95% 46 98% 51 99% 55 100% 1058 (longest request)

设定缓存加速

root@Nginx \~\]# vim /usr/local/nginx/conf/nginx.conf 28 #tcp_nopush on; 29 30 #keepalive_timeout 0; 31 keepalive_timeout 65; 32 proxy_cache_path /usr/local/nginx/proxy_cache levels=1:2:2 keys_zone=proxycache:20m inactive=120s max_size=1g; 33 #gzip on; 34 35 server { #添加32行信息 server { listen 80; server_name lee.hjw.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 #测试 \[root@Yhu \~\]# ab -n 10000 -c 50 lee.hjw.org/index.php This is ApacheBench, Version 2.3 \<$Revision: 1903618 $\> Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ Licensed to The Apache Software Foundation, http://www.apache.org/ Benchmarking lee.hjw.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.hjw.org Server Port: 80 Document Path: /index.php Document Length: 72827 bytes Concurrency Level: 50 Time taken for tests: 3.868 seconds Complete requests: 10000 Failed requests: 0 Total transferred: 729900000 bytes HTML transferred: 728270000 bytes Requests per second: 2585.06 \[#/sec\] (mean) Time per request: 19.342 \[ms\] (mean) Time per request: 0.387 \[ms\] (mean, across all concurrent requests) Transfer rate: 184261.31 \[Kbytes/sec\] received Connection Times (ms) min mean\[+/-sd\] median max Connect: 0 4 2.2 3 12 Processing: 2 15 4.9 16 34 Waiting: 0 6 2.9 5 19 Total: 3 19 4.7 20 34 Percentage of the requests served within a certain time (ms) 50% 20 66% 21 75% 22 80% 23 90% 25 95% 27 98% 29 99% 30 100% 34 (longest request) \[root@Nginx \~\]# tree /usr/local/nginx/proxy_cache/ /usr/local/nginx/proxy_cache/ └── 1 └── af └── 15 └── e251273eb74a8ee3f661a7af00915af1 3 directories, 1 file

反向代理负载均衡

Nginx在1.9.0版本开始支持tcp模式的负载均衡,在1.9.13版本开始支持udp协议的负载,udp主要用于 DNS的域名解析,其配置方式和指令和http 代理类似,其基于ngx_stream_proxy_module模块实现tcp 负载,另外基于模块ngx_stream_upstream_module实现后端服务器分组转发、权重分配、状态监测、 调度算法等高级功能。
如果编译安装,需要指定 --with-stream 选项才能支持ngx_stream_proxy_module模块
官方文档:
https://nginx.org/en/docs/stream/ngx_stream_proxy_module.html

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.hjw.org; location \~ / { proxy_pass http://webserver; } } \[root@Nginx \~\]# mkdir /web/hjw.org/error/html -p \[root@Nginx \~\]# echo error \> /web/hjw.org/error/html/index.html \[root@Nginx \~\]# vim /usr/local/nginx/conf/conf.d/vhosts.conf server { listen 8080; root /web/hjw.org/error/html; } #测试: \[root@Yhu \~\]# for i in {1..10};do curl lee.hjw.org;done 172.25.254.20 172.25.254.10 172.25.254.20 172.25.254.10 172.25.254.20 172.25.254.10 172.25.254.20 172.25.254.10 172.25.254.20 172.25.254.10 \[root@RS1+2 \~\]# systemctl stop httpd \[root@Yhu \~\]# for i in {1..10};do curl lee.hjw.org;done error error error error error error error error error error

实验环境(Mysql)

root@RS1 \~\]# dnf install mariadb-server -y \[root@RS2 \~\]# dnf install mariadb-server -y \[root@RS1 \~\]# vim /etc/my.cnf.d/mariadb-server.cnf server-id=10 \[root@RS2 \~\]# vim /etc/my.cnf.d/mariadb-server.cnf server-id=20 \[root@RS1 \~\]# systemctl enable --now mariadb \[root@RS2 \~\]# 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 hjw@'%' IDENTIFIED BY 'hjw'; Query OK, 0 rows affected (0.001 sec) MariaDB \[(none)\]\> GRANT ALL ON \*.\* TO lee@'%'; Query OK, 0 rows affected (0.001 sec) MariaDB \[(none)\]\> \[root@RS2 \~\]# 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 hjw@'%' IDENTIFIED BY 'hjw'; Query OK, 0 rows affected (0.001 sec) MariaDB \[(none)\]\> GRANT ALL ON \*.\* TO lee@'%'; Query OK, 0 rows affected (0.001 sec)

实验环境(dns)

root@RS1 \~\]# dnf install bind -y \[root@RS2 \~\]# dnf install bind -y \[root@RS1 \~\]# vim /etc/named.conf \[root@RS2 \~\]# vim /etc/named.conf options { // listen-on port 53 { 127.0.0.1; }; // listen-on-v6 port 53 { ::1; }; directory "/var/named"; dump-file "/var/named/data/cache_dump.db"; statistics-file "/var/named/data/named_stats.txt"; memstatistics-file "/var/named/data/named_mem_stats.txt"; secroots-file "/var/named/data/named.secroots"; recursing-file "/var/named/data/named.recursing"; // allow-query { localhost; }; dnssec-validation no; \[root@RS1 \~\]# vim /etc/named.rfc1912.zones \[root@RS2 \~\]# vim /etc/named.rfc1912.zones zone "hjw.org" IN { type master; file "hjw.org.zone"; allow-update { none; }; }; \[root@RS1 \~\]# cd /var/named/ \[root@RS2 \~\]# cd /var/named/ \[root@RS1 named\]# cp -p named.localhost hjw.org.zone \[root@RS2 named\]# cp -p named.localhost hjw.org.zone \[root@RS1 named\]# vim hjw.org.zone $TTL 1D @ IN SOA dns.hjw.org. rname.invalid. ( 0 ; serial 1D ; refresh 1H ; retry 1W ; expire 3H ) ; minimum NS dns.hjw.org. dns A 172.25.254.10 \[root@RS2 named\]# vim hjw.org.zone $TTL 1D @ IN SOA dns.hjw.org. rname.invalid. ( 0 ; serial 1D ; refresh 1H ; retry 1W ; expire 3H ) ; minimum NS dns.hjw.org. dns A 172.25.254.20 \[root@RS2 named\]# systemctl enable --now named #测试 \[root@RS1 named\]# vim /etc/named.r named.rfc1912.zones named.root.key \[root@RS1 named\]# vim /etc/named.rfc1912.zones \[root@RS1 named\]# systemctl enable --now named Created symlink /etc/systemd/system/multi-user.target.wants/named.service → /usr/lib/systemd/system/named.service. \[root@RS1 named\]# cd \[root@RS1 \~\]# dig dns.hjw.org @172.25.254.10 ; \<\<\>\> DiG 9.16.23-RH \<\<\>\> dns.hjw.org @172.25.254.10 ;; global options: +cmd ;; Got answer: ;; -\>\>HEADER\<\<- opcode: QUERY, status: NOERROR, id: 5132 ;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1 ;; OPT PSEUDOSECTION: ; EDNS: version: 0, flags:; udp: 1232 ; COOKIE: e3251090f7f942c801000000698306b4b0bcb2269b14ec2c (good) ;; QUESTION SECTION: ;dns.hjw.org. IN A ;; ANSWER SECTION: dns.hjw.org. 86400 IN A 172.25.254.10 ;; Query time: 1 msec ;; SERVER: 172.25.254.10#53(172.25.254.10) ;; WHEN: Wed Feb 04 16:43:32 CST 2026 ;; MSG SIZE rcvd: 84 \[root@RS1 \~\]# dig dns.hjw.org @172.25.254.20 ; \<\<\>\> DiG 9.16.23-RH \<\<\>\> dns.hjw.org @172.25.254.20 ;; global options: +cmd ;; Got answer: ;; -\>\>HEADER\<\<- opcode: QUERY, status: NOERROR, id: 32855 ;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1 ;; WARNING: recursion requested but not available ;; OPT PSEUDOSECTION: ; EDNS: version: 0, flags:; udp: 1232 ; COOKIE: b07eee685da11b0c01000000698306c9d37a266c1549c760 (good) ;; QUESTION SECTION: ;dns.hjw.org. IN A ;; ANSWER SECTION: dns.hjw.org. 86400 IN A 172.25.254.20 ;; Query time: 5 msec ;; SERVER: 172.25.254.20#53(172.25.254.20) ;; WHEN: Wed Feb 04 16:43:53 CST 2026 ;; MSG SIZE rcvd: 84

tcp四层负载

root@Nginx conf\]# mkdir /usr/local/nginx/conf/tcp -p \[root@Nginx conf\]# mkdir /usr/local/nginx/conf/udp -p \[root@Nginx conf\]# vim /usr/local/nginx/conf/nginx.conf include "/usr/local/nginx/conf/tcp/\*.conf"; \[root@Nginx conf\]# vim /usr/local/nginx/conf/tcp/mariadb.conf stream { upstream mysql_server { server 172.25.254.10:3306 max_fails=3 fail_timeout=30s; server 172.25.254.20:3306 max_fails=3 fail_timeout=30s; } server { listen 172.25.254.100:3306; proxy_pass mysql_server; proxy_connect_timeout 30s; proxy_timeout 300s; } } \[root@Nginx conf\]# nginx -s reload #检测 \[root@Yhu \~\]# mysql -uhjw -phjw -h172.25.254.100 Welcome to the MariaDB monitor. Commands end with ; or \\g. Your MariaDB connection id is 6 Server version: 10.5.16-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)\]\> SELECT @@server_id; +-------------+ \| @@server_id \| +-------------+ \| 20 \| +-------------+ 1 row in set (0.002 sec) MariaDB \[(none)\]\> Ctrl-C -- exit! Aborted \[root@Yhu \~\]# mysql -uhjw -phjw -h172.25.254.100 Welcome to the MariaDB monitor. Commands end with ; or \\g. Your MariaDB connection id is 8 Server version: 10.5.16-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)\]\> SELECT @@server_id; +-------------+ \| @@server_id \| +-------------+ \| 10 \| +-------------+ 1 row in set (0.002 sec) MariaDB \[(none)\]\>

root@Nginx \~\]# vim /usr/local/nginx/conf/tcp/mariadb.conf stream { upstream mysql_server { server 172.25.254.10:3306 max_fails=3 fail_timeout=30s; server 172.25.254.20:3306 max_fails=3 fail_timeout=30s; } upstream dns_server{ server 172.25.254.10:53 max_fails=3 fail_timeout=30s; server 172.25.254.20:53 max_fails=3 fail_timeout=30s; } server { listen 172.25.254.100:3306; proxy_pass mysql_server; proxy_connect_timeout 30s; proxy_timeout 300s; } server { listen 172.25.254.100:53 udp; proxy_pass dns_server; proxy_timeout 1s; proxy_responses 1; error_log logs/dns.log; } } \[root@Nginx \~\]# nginx -s reload #测试 \[root@Yhu \~\]# dig dns.hjw.org @172.25.254.100 ; \<\<\>\> DiG 9.16.23-RH \<\<\>\> dns.hjw.org @172.25.254.100 ;; global options: +cmd ;; Got answer: ;; -\>\>HEADER\<\<- opcode: QUERY, status: NOERROR, id: 39940 ;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1 ;; OPT PSEUDOSECTION: ; EDNS: version: 0, flags:; udp: 1232 ; COOKIE: 3042a3ccea4255840100000069830975482c8980359e1df0 (good) ;; QUESTION SECTION: ;dns.hjw.org. IN A ;; ANSWER SECTION: dns.hjw.org. 86400 IN A 172.25.254.10 ;; Query time: 4 msec ;; SERVER: 172.25.254.100#53(172.25.254.100) ;; WHEN: Wed Feb 04 16:55:17 CST 2026 ;; MSG SIZE rcvd: 84 \[root@Yhu \~\]# dig dns.hjw.org @172.25.254.100 ; \<\<\>\> DiG 9.16.23-RH \<\<\>\> dns.hjw.org @172.25.254.100 ;; global options: +cmd ;; Got answer: ;; -\>\>HEADER\<\<- opcode: QUERY, status: NOERROR, id: 56309 ;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1 ;; WARNING: recursion requested but not available ;; OPT PSEUDOSECTION: ; EDNS: version: 0, flags:; udp: 1232 ; COOKIE: 87800bfd2fb054a501000000698309a76c1c64807b2675af (good) ;; QUESTION SECTION: ;dns.hjw.org. IN A ;; ANSWER SECTION: dns.hjw.org. 86400 IN A 172.25.254.20 ;; Query time: 1 msec ;; SERVER: 172.25.254.100#53(172.25.254.100) ;; WHEN: Wed Feb 04 16:56:07 CST 2026 ;; MSG SIZE rcvd: 84

重新编译nginx

root@Nginx \~\]# systemctl stop nginx.service \[root@Nginx \~\]# cp /usr/local/nginx/conf/ /mnt/ -r \[root@Nginx \~\]# rm -fr /usr/local/nginx/ \[root@Nginx \~\]# rm -rf nginx-1.29.4 nginx-1.28.1 \[root@Nginx \~\]# tar zxf nginx-1.28.1.tar.gz \[root@Nginx \~\]# cd nginx-1.28.1/ \[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/memc-nginx-module-0.20 --add-module=/root/srcache-nginx-module-0.33 \[root@Nginx nginx-1.28.1\]# make \&\& make install \[root@Nginx \~\]# cd /usr/local/nginx/conf \[root@Nginx conf\]# cp /mnt/conf/nginx.conf /usr/conf/conf.d/ -r \[root@Nginx \~\]#cp /mnt/conf/nginx.conf /usr/local/nginx/conf/nginx.conf \[root@Nginx conf\]# systemctl start nginx.service

整合memcache

root@Nginx conf\]# vim /usr/local/nginx/conf/conf.d/php.conf upstream memcache { server 127.0.0.1:11211; keepalive 512; } server { listen 80; server_name php.hjw.org; root /web/hjw.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; } } \[root@Nginx conf\]# nginx -s reload #测试 \[root@Nginx conf\]# ab -n 10000 -c500 http://php.hjw.org/example.php

编译安装 openresty

Nginx 是俄罗斯人发明的, Lua 是巴西几个教授发明的,中国人章亦春把 LuaJIT VM 嵌入到 Nginx 中, 实现了 OpenResty 这个高性能服务端解决方案
OpenResty® 是一个基于 Nginx 与 Lua 的高性能 Web 平台,其内部集成了大量精良的 Lua 库、第三方 模块以及大多数的依赖项。用于方便地搭建能够处理超高并发、扩展性极高的动态 Web 应用、Web 服 务和动态网关。
OpenResty® 通过汇聚各种设计精良的 Nginx 模块(主要由 OpenResty 团队自主开发),从而将Nginx 有效地变成一个强大的通用 Web 应用平台。这样,Web 开发人员和系统工程师可以使用 Lua 脚本语言 调动 Nginx 支持的各种 C 以及 Lua 模块,快速构造出足以胜任 10K 乃至 1000K 以上单机并发连接的高 性能 Web 应用系统。
OpenResty 由于有功能强大且方便的的API,可扩展性更强,如果需要实现定制功能,OpenResty是个不错的
选择
官网: http://openresty.org/cn/

root@Nginx src\]#wget https://openresty.org/download/openresty-1.27.1.2.tar.gz \[root@Nginx \~\]#dnf -yq install gcc pcre-devel openssl-devel perl zlib-devel \[root@Nginx \~\]#useradd -r -s /sbin/nologin nginx \[root@Nginx \~\]#tar zxf openresty-1.27.1.2 \[root@webserver \~\]# cd openresty-1.27.1.2/ \[root@Nginx openresty-1.17.8.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.17.8.2\]#gmake \&\& gmake install \[root@webserver openresty\]# vim \~/.bash_profile export PATH=$PATH:/usr/local/openresty/bin \[root@webserver openresty\]#source \~/.bash_profile \[root@Nginx openresty-1.17.8.2\]#openresty -v nginx version: openresty/1.17.8.2 \[root@Nginx openresty-1.17.8.2\]#openresty \[root@Nginx openresty-1.17.8.2\]#ps -ef \|grep nginx \[root@webserver openresty\]# echo hello test \> /usr/local/openresty/nginx/html/index.html \[root@webserver openresty\]# curl 172.25.254.200 hello test

相关推荐
汇智信科1 小时前
汇智信科网络考试系统:以技术赋能,重构在线测评新范式
linux·数据库·mysql·oracle·sqlserver·java技术
码农编程录1 小时前
【notes14】debugfs
linux
数据与人1 小时前
Linux中Too many open files错误的解决
linux·服务器·前端
Joren的学习记录1 小时前
【Linux运维大神系列】k8s项目部署实战
linux·运维·kubernetes
杰克崔1 小时前
android的lmkd的实现及代码分析
android·linux·运维·服务器·车载系统
Codefengfeng1 小时前
webshell流量分析-Practice1
linux·web安全
BullSmall1 小时前
从2026年春晚 详细分析未来IT行业的发展
linux·运维·服务器·数据库
星融元asterfusion1 小时前
打破“黑盒”:RoCE小工具为RDMA网络运维带来可视化曙光
运维·rdma·会话追踪
Exquisite.1 小时前
4、云原生 --- nginx
运维·nginx