高性能web服务器---Nginx

一、web服务器基础

1.web服务器介绍

1.1 Apache 经典的 Web 服务端

Apache起初由美国的伊利诺伊大学香槟分校的国家超级计算机应用中心开发

目前经历了两大版本分别是1.X和2.X

其可以通过编译安装实现特定的功能

1.1.1 Apache prefork 模型

预派生模式,有一个主控制进程,然后生成多个子进程,使用select模型,最大并发1024

每个子进程有一个独立的线程响应用户请求

相对比较占用内存,但是比较稳定,可以设置最大和最小进程数

是最古老的一种模式,也是最稳定的模式,适用于访问量不是很大的场景

优点:稳定 缺点:每个用户请求需要对应开启一个进程,占用资源较多,并发性差,不适用于高并发场景

1.1.2 Apache worker 模型

一种多进程和多线程混合的模型

有一个控制进程,启动多个子进程

每个子进程里面包含固定的线程

使用线程程来处理请求

当线程不够使用的时候会再启动一个新的子进程,然后在进程里面再启动线程处理请求,

由于其使用了线程处理请求,因此可以承受更高的并发

优点:相比prefork 占用的内存较少,可以同时处理更多的请求

缺点:使用keepalive的长连接方式,某个线程会一直被占据,即使没有传输数据,也需要一直等待到超 时才会被释放。如果过多的线程,被这样占据,也会导致在高并发场景下的无服务线程可用(该问题在 prefork模式下,同样会发生)

1.1.3 Apache event模型

Apache中最新的模式,2012年发布的apache 2.4.X系列正式支持event 模型,属于事件驱动模型(epoll) 每个进程响应多个请求,在现在版本里的已经是稳定可用的模式

它和worker模式很像,最大的区别在于,它解决了keepalive场景下长期被占用的线程的资源浪费问题 (某些线程因为被keepalive,空挂在哪里等待,中间几乎没有请求过来,甚至等到超时)

event MPM中,会有一个专门的线程来管理这些keepalive类型的线程

当有真实请求过来的时候,将请求传递给服务线程,执行完毕后,又允许它释放。这样增强了高并发场 景下的请求处理能力

优点:单线程响应多请求,占据更少的内存,高并发下表现更优秀,会有一个专门的线程来管理keepalive类型的线程,当有真实请求过来的时候,将请求传递给服务线程,执行完毕后,又允许它释放

缺点:没有线程安全控制

1.2 服务端 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 : 一切皆文件,本质为对socket文件的读写

1.2.1磁盘I/O

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

1.2.2网络I/O

网络通信就是网络协议栈到用户空间进程的IO就是网络IO

网络I/O 处理过程

获取请求数据,客户端与服务器建立连接发出请求,服务器接受请求(1-3) 构建响应,当服务器接收完请求,并在用户空间处理客户端的请求,直到构建响应完成(4) 返回数据,服务器将已构建好的响应再通过内核空间的网络 I/O 发还给客户端(5-7)

不论磁盘和网络I/O

每次I/O,都要经由两个阶段:

第一步:将数据从文件先加载至内核内存空间(缓冲区),等待数据准备完成,时间较长

第二步:将数据从内核缓冲区复制到用户空间的进程的内存中,时间较短

1.3 I/O模型
1.3.1 I/O模型相关概念

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

同步:synchronous,被调用者并不提供事件的处理结果相关的通知消息,需要调用者主动询问事 情是否处理完成

异步:asynchronous,被调用者通过状态、通知或回调机制主动通知调用者被调用者的运行状态

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

阻塞:blocking,指IO操作需要彻底完成后才返回到用户空间,调用结果返回之前,调用者被挂 起,干不了别的事情。

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

二、Ngina架构和安装

1.Nginx概述

1.1Nginx介绍

Nginx:engine X ,2002年开发,分为社区版和商业版(nginx plus ) 2019年3月11日 F5 Networks 6.7亿美元的价格收购

Nginx是免费的、开源的、高性能的HTTP和反向代理服务器、邮件代理服务器、以及TCP/UDP代理服务器

解决C10K问题(10K Connections)

Nginx官网:nginx news

1.2Nginx功能介绍

静态的web资源服务器html,图片,js,css,txt等静态资源

http/https协议的反向代理

结合FastCGI/uWSGI/SCGI等协议反向代理动态资源请求

tcp/udp协议的请求转发(反向代理)

imap4/pop3协议的反向代理

1.3基础特性

模块化设计,较好的扩展性

高可靠性

支持热部署:不停机更新配置文件,升级版本,更换日志文件

低内存消耗:10000个keep-alive连接模式下的非活动连接,仅需2.5M内存

event-driven,aio,mmap,sendfile

2.Nginx架构进程

3.Nginx安装

3.1 Nginx版本和安装方式

Nginx版本

Mainline version 主要开发版本,一般为奇数版本号,比如1.19; Stable version 当前最新稳定版,一般为偶数版本,如:1.20 Legacy versions; 旧的稳定版,一般为偶数版本,如:1.18 Nginx安装可以使用yum或源码安装,但是推荐使用源码编译安装。 yum的版本比较旧 ;编译安装可以更方便自定义相关路径; 使用源码编译可以自定义相关功能,更方便业务的上的使用

3.2 Nginx编译安装

官方源码下载地址:

nginx: download

编译安装:

1.提前准备好nginx安装包nginx-1.24.0.tar.gz:
[root@nginx-node1 ~]# tar zxf nginx-1.24.0.tar.gz
[root@nginx-node1 ~]# ls
公共  视频  文档  音乐  anaconda-ks.cfg  nginx-1.24.0.tar.gz
模板  图片  下载  桌面  nginx-1.24.0
[root@nginx-node1 ~]# cd nginx-1.24.0/
[root@nginx-node1 nginx-1.24.0]# ls
auto  CHANGES  CHANGES.ru  conf  configure  contrib  html  LICENSE  man  README  src
​
configure检测
[root@nginx-node1 nginx-1.24.0]# dnf install gcc pcre-devel zlib-devel openssl-devel -y
[root@nginx-node1 nginx-1.24.0]# ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_gzip_static_module --with-http_stub_status_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module
​
Configuration summary
  + using system PCRE library
  + using system OpenSSL library
  + using system zlib library
​
  nginx path prefix: "/usr/local/nginx"
  nginx binary file: "/usr/local/nginx/sbin/nginx"
  nginx modules path: "/usr/local/nginx/modules"
  nginx configuration prefix: "/usr/local/nginx/conf"
  nginx configuration file: "/usr/local/nginx/conf/nginx.conf"
  nginx pid file: "/usr/local/nginx/logs/nginx.pid"
  nginx error log file: "/usr/local/nginx/logs/error.log"
  nginx http access log file: "/usr/local/nginx/logs/access.log"
  nginx http client request body temporary files: "client_body_temp"
  nginx http proxy temporary files: "proxy_temp"
  nginx http fastcgi temporary files: "fastcgi_temp"
  nginx http uwsgi temporary files: "uwsgi_temp"
  nginx http scgi temporary files: "scgi_temp"
​
安装完成
​
下载好后会有Makefile  objs 
​
[root@nginx-node1 nginx-1.24.0]# ls
auto     CHANGES.ru  configure  html     Makefile  objs    src
CHANGES  conf        contrib    LICENSE  man       README
[root@nginx-node1 nginx-1.24.0]# cd objs/
[root@nginx-node1 objs]# ls
autoconf.err  Makefile  ngx_auto_config.h  ngx_auto_headers.h  ngx_modules.c  src
[root@nginx-node1 objs]# cd ..
​
编译
[root@nginx-node1 nginx-1.24.0]# make -j2
​
编译完成后
[root@nginx-node1 nginx-1.24.0]# ls
auto     CHANGES.ru  configure  html     Makefile  objs    src
CHANGES  conf        contrib    LICENSE  man       README
[root@nginx-node1 nginx-1.24.0]# cd objs/
[root@nginx-node1 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-node1 objs]# cd src/
[root@nginx-node1 src]# ls
core  event  http  mail  misc  os  stream
[root@nginx-node1 src]# cd stream/
​
nginx模块
[root@nginx-node1 stream]# ls
ngx_stream_access_module.o      ngx_stream_set_module.o
ngx_stream_core_module.o        ngx_stream_split_clients_module.o
ngx_stream_geo_module.o         ngx_stream_ssl_module.o
ngx_stream_handler.o            ngx_stream_upstream_hash_module.o
ngx_stream_limit_conn_module.o  ngx_stream_upstream_least_conn_module.o
ngx_stream_log_module.o         ngx_stream_upstream.o
ngx_stream_map_module.o         ngx_stream_upstream_random_module.o
ngx_stream.o                    ngx_stream_upstream_round_robin.o
ngx_stream_proxy_module.o       ngx_stream_upstream_zone_module.o
ngx_stream_realip_module.o      ngx_stream_variables.o
ngx_stream_return_module.o      ngx_stream_write_filter_module.o
ngx_stream_script.o
[root@nginx-node1 nginx-1.24.0]# ls
auto     CHANGES.ru  configure  html     Makefile  objs    src
CHANGES  conf        contrib    LICENSE  man       README
[root@nginx-node1 nginx-1.24.0]# make install
make -f objs/Makefile install
make[1]: 进入目录“/root/nginx-1.24.0”
test -d '/usr/local/nginx' || mkdir -p '/usr/local/nginx'
test -d '/usr/local/nginx/sbin' \
        || mkdir -p '/usr/local/nginx/sbin'
test ! -f '/usr/local/nginx/sbin/nginx' \
        || mv '/usr/local/nginx/sbin/nginx' \
                '/usr/local/nginx/sbin/nginx.old'
cp objs/nginx '/usr/local/nginx/sbin/nginx'
test -d '/usr/local/nginx/conf' \
        || mkdir -p '/usr/local/nginx/conf'
cp conf/koi-win '/usr/local/nginx/conf'
cp conf/koi-utf '/usr/local/nginx/conf'
cp conf/win-utf '/usr/local/nginx/conf'
test -f '/usr/local/nginx/conf/mime.types' \
        || cp conf/mime.types '/usr/local/nginx/conf'
cp conf/mime.types '/usr/local/nginx/conf/mime.types.default'
test -f '/usr/local/nginx/conf/fastcgi_params' \
        || cp conf/fastcgi_params '/usr/local/nginx/conf'
cp conf/fastcgi_params \
        '/usr/local/nginx/conf/fastcgi_params.default'
test -f '/usr/local/nginx/conf/fastcgi.conf' \
        || cp conf/fastcgi.conf '/usr/local/nginx/conf'
cp conf/fastcgi.conf '/usr/local/nginx/conf/fastcgi.conf.default'
test -f '/usr/local/nginx/conf/uwsgi_params' \
        || cp conf/uwsgi_params '/usr/local/nginx/conf'
cp conf/uwsgi_params \
        '/usr/local/nginx/conf/uwsgi_params.default'
test -f '/usr/local/nginx/conf/scgi_params' \
        || cp conf/scgi_params '/usr/local/nginx/conf'
cp conf/scgi_params \
        '/usr/local/nginx/conf/scgi_params.default'
test -f '/usr/local/nginx/conf/nginx.conf' \
        || cp conf/nginx.conf '/usr/local/nginx/conf/nginx.conf'
cp conf/nginx.conf '/usr/local/nginx/conf/nginx.conf.default'
test -d '/usr/local/nginx/logs' \
        || mkdir -p '/usr/local/nginx/logs'
test -d '/usr/local/nginx/logs' \
        || mkdir -p '/usr/local/nginx/logs'
test -d '/usr/local/nginx/html' \
        || cp -R html '/usr/local/nginx'
test -d '/usr/local/nginx/logs' \
        || mkdir -p '/usr/local/nginx/logs'
make[1]: 离开目录“/root/nginx-1.24.0”
[root@nginx-node1 nginx-1.24.0]# cd /usr/local/nginx/
[root@nginx-node1 nginx]# ls
client_body_temp  fastcgi_temp  logs        sbin       uwsgi_temp
conf              html          proxy_temp  scgi_temp
[root@nginx-node1 nginx]# cd sbin/
[root@nginx-node1 sbin]# ls
nginx 
[root@nginx-node1 sbin]# /usr/local/nginx/sbin/nginx
[root@nginx-node1 sbin]# useradd -s /sbin/nologin -M nginx
[root@nginx-node1 sbin]# id nginx
用户id=1001(nginx) 组id=1001(nginx) 组=1001(nginx)
[root@nginx-node1 sbin]# ll
总用量 11096
-rwxr-xr-x 1 root root 5679504  8月 15 18:25 nginx
​
启动nginx
[root@nginx-node1 sbin]# ./nginx
​
查看进程
[root@nginx-node1 sbin]# ps aux | grep nginx
root       37057  0.0  0.0   9836   932 ?        Ss   20:14   0:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx      37058  0.0  0.1  13724  5352 ?        S    20:14   0:00 nginx: worker process
root       37066  0.0  0.0 221680  2360 pts/0    S+   20:16   0:00 grep --color=auto nginx
​
查看端口
[root@nginx-node1 sbin]# netstat -antlupe | grep nginx
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      0          68910      41867/nginx: master
​
查看nginx大小
[root@nginx-node1 sbin]# du -sh nginx
5.5M    nginx
​
关闭nginx
[root@nginx-node1 sbin]# /usr/local/nginx/sbin/nginx -s stop
[root@nginx-node1 sbin]# killall -9 nginx
[root@nginx-node1 sbin]# netstat -antlupe | grep nginx
​
重启nginx
[root@nginx-node1 sbin]# /usr/local/nginx/sbin/nginx -s restart
​
删除nginx
[root@nginx-node1 nginx-1.24.0]# rm -fr /usr/local/nginx/
[root@nginx-node1 nginx-1.24.0]# make clean
rm -rf Makefile objs
[root@nginx-node1 nginx-1.24.0]#
[root@nginx-node1 nginx-1.24.0]# ls
auto  CHANGES  CHANGES.ru  conf  configure  contrib  html  LICENSE  man  README  src
​
关闭debug功能
[root@nginx-node1 nginx-1.24.0]# vim auto/
cc/           have          init          module        os/           threads
define        have_headers  install       modules       sources       types/
endianness    headers       lib/          nohave        stubs         unix
feature       include       make          options       summary
[root@nginx-node1 nginx-1.24.0]# vim auto/cc/
acc    bcc    ccc    clang  conf   gcc    icc    msvc   name   owc    sunc
[root@nginx-node1 nginx-1.24.0]# vim auto/cc/gcc
​
​
重新编译
[root@nginx-node1 nginx-1.24.0]# ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_gzip_static_module --with-http_stub_status_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module
​
下载
[root@nginx-node1 nginx-1.24.0]# make && make install
[root@nginx-node1 nginx-1.24.0]# cd
​
将nginx软件的命令执行路径添加到环境变量中
[root@nginx-node1 ~]# vim ~/.bash_profile
export PATH=$PATH:/usr/local/nginx/sbin
[root@nginx-node1 ~]# source ~/.bash_profile 
​
nginx变小
[root@nginx-node1 ~]# du -sh /usr/local/nginx/sbin/nginx
1.2M    /usr/local/nginx/sbin/nginx
​
[root@nginx-node1 ~]# cd /usr/local/nginx/
[root@nginx-node1 nginx]# ls
conf  html  logs  sbin
[root@nginx-node1 nginx]# cd conf/
[root@nginx-node1 conf]# ls
fastcgi.conf            koi-utf             nginx.conf           uwsgi_params
fastcgi.conf.default    koi-win             nginx.conf.default   uwsgi_params.default
fastcgi_params          mime.types          scgi_params          win-utf
fastcgi_params.default  mime.types.default  scgi_params.default
​
启动nginx
[root@nginx-node1 conf]# nginx
​
[root@nginx-node1 conf]# curl -I 172.25.254.100
HTTP/1.1 200 OK
Server: nginx/1.20.1
Date: Thu, 15 Aug 2024 10:42:58 GMT
Content-Type: text/html
Content-Length: 5909
Last-Modified: Mon, 09 Aug 2021 11:43:42 GMT
Connection: keep-alive
ETag: "611114ee-1715"
Accept-Ranges: bytes

可以更改隐藏nginx的版本和变量

[root@nginx-node1 ~]# ls
公共  图片  音乐             echo-nginx-module-0.63         nginx-1.24.0.tar.gz
模板  文档  桌面             echo-nginx-module-0.63.tar.gz  nginx-1.26.1
视频  下载  anaconda-ks.cfg  nginx-1.24.0                   nginx-1.26.1.tar.gz
[root@nginx-node1 ~]# cd nginx-1.24.0/
[root@nginx-node1 nginx-1.24.0]# ls
auto     CHANGES.ru  configure  html     Makefile  objs    src
CHANGES  conf        contrib    LICENSE  man       README
[root@nginx-node1 nginx-1.24.0]# cd src/
[root@nginx-node1 src]# ls
core  event  http  mail  misc  os  stream
[root@nginx-node1 src]# cd core/
​
nginx源码
[root@nginx-node1 core]# ls
nginx.c           ngx_cycle.h            ngx_output_chain.c    ngx_rwlock.c
nginx.h           ngx_file.c             ngx_palloc.c          ngx_rwlock.h
ngx_array.c       ngx_file.h             ngx_palloc.h          ngx_sha1.c
ngx_array.h       ngx_hash.c             ngx_parse.c           ngx_sha1.h
ngx_buf.c         ngx_hash.h             ngx_parse.h           ngx_shmtx.c
ngx_buf.h         ngx_inet.c             ngx_parse_time.c      ngx_shmtx.h
ngx_conf_file.c   ngx_inet.h             ngx_parse_time.h      ngx_slab.c
ngx_conf_file.h   ngx_list.c             ngx_proxy_protocol.c  ngx_slab.h
ngx_config.h      ngx_list.h             ngx_proxy_protocol.h  ngx_spinlock.c
ngx_connection.c  ngx_log.c              ngx_queue.c           ngx_string.c
ngx_connection.h  ngx_log.h              ngx_queue.h           ngx_string.h
ngx_core.h        ngx_md5.c              ngx_radix_tree.c      ngx_syslog.c
ngx_cpuinfo.c     ngx_md5.h              ngx_radix_tree.h      ngx_syslog.h
ngx_crc32.c       ngx_module.c           ngx_rbtree.c          ngx_thread_pool.c
ngx_crc32.h       ngx_module.h           ngx_rbtree.h          ngx_thread_pool.h
ngx_crc.h         ngx_murmurhash.c       ngx_regex.c           ngx_times.c
ngx_crypt.c       ngx_murmurhash.h       ngx_regex.h           ngx_times.h
ngx_crypt.h       ngx_open_file_cache.c  ngx_resolver.c
ngx_cycle.c       ngx_open_file_cache.h  ngx_resolver.h
[root@nginx-node1 core]# vim nginx.h

4.平滑升级和回滚

4.1 平滑升级
[root@nginx-node1 ~]# ls
公共  图片  音乐             echo-nginx-module-0.63.tar.gz  nginx-1.26.1.tar.gz
模板  文档  桌面             nginx-1.24.0
视频  下载  anaconda-ks.cfg  nginx-1.24.0.tar.gz
[root@nginx-node1 ~]# tar zxf nginx-1.26.1.tar.gz
[root@nginx-node1 ~]# tar zxf echo-nginx-module-0.63.tar.gz
[root@nginx-node1 ~]# ls
公共  图片  音乐             echo-nginx-module-0.63         nginx-1.24.0.tar.gz
模板  文档  桌面             echo-nginx-module-0.63.tar.gz  nginx-1.26.1
视频  下载  anaconda-ks.cfg  nginx-1.24.0     
[root@nginx-node1 ~]# cd nginx-1.26.1/
[root@nginx-node1 nginx-1.26.1]# ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --add-module=/root/echo-nginx-module-0.63 --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_gzip_static_module --with-http_stub_status_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module
​
编译,直接make,不能make && make install
[root@nginx-node1 nginx-1.26.1]#make
​
[root@nginx-node1 nginx-1.26.1]# ls
auto     CHANGES.ru  configure  html     Makefile  objs    src
CHANGES  conf        contrib    LICENSE  man       README
[root@nginx-node1 nginx-1.26.1]# cd objs/
[root@nginx-node1 objs]# ls
addon         Makefile  nginx.8            ngx_auto_headers.h  ngx_modules.o
autoconf.err  nginx     ngx_auto_config.h  ngx_modules.c       src
[root@nginx-node1 objs]# cd /usr/local/nginx/
[root@nginx-node1 nginx]# ls
client_body_temp  conf  fastcgi_temp  html  logs  proxy_temp  sbin  scgi_temp  uwsgi_temp
[root@nginx-node1 nginx]# cd /usr/local/nginx/sbin/
[root@nginx-node1 sbin]# ls
nginx
​
启动nginx
[root@nginx-node1 sbin]# nginx
​
[root@nginx-node1 sbin]# curl -I 172.25.254.100
HTTP/1.1 200 OK
Server: nginx/1.24.0
Date: Thu, 15 Aug 2024 12:32:57 GMT
Content-Type: text/html
Content-Length: 615
Last-Modified: Thu, 15 Aug 2024 12:20:44 GMT
Connection: keep-alive
ETag: "66bdf29c-267"
Accept-Ranges: bytes
​
把旧版本的nginx命令备份
[root@nginx-node1 sbin]# cp nginx nginx.old
​
把新版本的nginx命令复制过去
[root@nginx-node1 sbin]# \cp -f /root/nginx-1.26.1/objs/nginx  /usr/local/nginx/sbin/
[root@nginx-node1 sbin]# ll
总用量 7252
-rwxr-xr-x 1 root root 6177456  8月 15 20:34 nginx
-rwxr-xr-x 1 root root 1242720  8月 15 20:33 nginx.old
[root@nginx-node1 sbin]# ps aux | grep nginx
root       37057  0.0  0.0   9836   932 ?        Ss   20:14   0:00 nginx: master process /usr/l  ocal/nginx/sbin/nginx
nginx      37058  0.0  0.1  13724  5352 ?        S    20:14   0:00 nginx: worker process
root       43455  0.0  0.0 221680  2336 pts/0    S+   20:34   0:00 grep --color=auto nginx
​
检查有没有问题
[root@nginx-node1 sbin]# 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-node1 sbin]# ps aux | grep nginx
root       37057  0.0  0.0   9836   932 ?        Ss   20:14   0:00 nginx: master process /usr/l  ocal/nginx/sbin/nginx
nginx      37058  0.0  0.1  13724  5352 ?        S    20:14   0:00 nginx: worker process
root       43455  0.0  0.0 221680  2336 pts/0    S+   20:34   0:00 grep --color=auto nginx
​
平滑升级,主进程ID
[root@nginx-node1 sbin]# kill -USR2 37057
[root@nginx-node1 sbin]# ps aux | grep nginx
root       37057  0.0  0.0   9836  2656 ?        Ss   20:14   0:00 nginx: master process /usr/l  ocal/nginx/sbin/nginx
nginx      37058  0.0  0.1  13724  5352 ?        S    20:14   0:00 nginx: worker process
root       43460  0.0  0.1   9872  6060 ?        S    20:38   0:00 nginx: master process /usr/l  ocal/nginx/sbin/nginx
nginx      43461  0.0  0.1  13760  4808 ?        S    20:38   0:00 nginx: worker process
root       43463  0.0  0.0 221680  2244 pts/0    S+   20:38   0:00 grep --color=auto nginx
​
回收旧版本
[root@nginx-node1 sbin]# kill -WINCH  37057
[root@nginx-node1 sbin]# ps aux | grep ngi
root       37057  0.0  0.0   9836  2656 ?        Ss   20:14   0:00 nginx: master process /usr/l  ocal/nginx/sbin/nginx
root       43460  0.0  0.1   9872  6060 ?        S    20:38   0:00 nginx: master process /usr/l  ocal/nginx/sbin/nginx
nginx      43461  0.0  0.1  13760  5344 ?        S    20:38   0:00 nginx: worker process
root       43466  0.0  0.0 221680  2228 pts/0    S+   20:41   0:00 grep --color=auto ngi
​
检测信息,新版本生效
[root@nginx-node1 ~]# curl -I 172.25.254.100
HTTP/1.1 200 OK
Server: nginx/1.26.1
Date: Thu, 15 Aug 2024 12:42:32 GMT
Content-Type: text/html
Content-Length: 615
Last-Modified: Thu, 15 Aug 2024 12:20:44 GMT
Connection: keep-alive
ETag: "66bdf29c-267"
Accept-Ranges: bytes
 

客户端一直运行,不会发现变化

4.2 平滑回滚

如果升级的版本发现问题需要回滚,可以重新拉起旧版本的worker

回到旧版本

拉起旧版本
[root@nginx-node1 sbin]# kill -HUP  37057
[root@nginx-node1 sbin]# ps aux | grep ngi
root       37057  0.0  0.0   9836  2656 ?        Ss   20:14   0:00 nginx: master process /usr/local/nginx/sbin/nginx
root       43460  0.0  0.1   9872  6060 ?        S    20:38   0:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx      43461  0.0  0.1  13760  5344 ?        S    20:38   0:00 nginx: worker process
nginx      43526  0.0  0.1  13724  5352 ?        S    20:44   0:00 nginx: worker process
root       43528  0.0  0.0 221680  2328 pts/0    S+   20:44   0:00 grep --color=auto ngi
​
回收新版本
[root@nginx-node1 sbin]# kill -WINCH  43460
​
[root@nginx-node1 sbin]# ps aux | grep ngi
root       37057  0.0  0.0   9836  2656 ?        Ss   20:14   0:00 nginx: master process /usr/local/nginx/sbin/nginx
root       43460  0.0  0.1   9872  6060 ?        S    20:38   0:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx      43526  0.0  0.1  13724  5352 ?        S    20:44   0:00 nginx: worker process
root       43530  0.0  0.0 221680  2352 pts/0    S+   20:45   0:00 grep --color=auto ngi
[root@nginx-node1 sbin]# ls
nginx  nginx.old
[root@nginx-node1 sbin]# cp nginx nginx.new
[root@nginx-node1 sbin]# ls
nginx  nginx.new  nginx.old
[root@nginx-node1 sbin]# \cp -f nginx.old nginx
[root@nginx-node1 sbin]# ls
nginx  nginx.new  nginx.old
[root@nginx-node1 sbin]# ps aux | grep nginx
root       37057  0.0  0.0   9836  2656 ?        Ss   20:14   0:00 nginx: master process /usr/local/nginx/sbin/nginx
root       43460  0.0  0.1   9872  6060 ?        S    20:38   0:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx      43526  0.0  0.1  13724  5352 ?        S    20:44   0:00 nginx: worker process
root       43544  0.0  0.0 221680  2348 pts/0    S+   20:47   0:00 grep --color=auto ngi
​
删除新版本
[root@nginx-node1 sbin]# kill -9 43460
[root@nginx-node1 sbin]# ps aux | grep nginx
root       37057  0.0  0.0   9836  2656 ?        Ss   20:14   0:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx      43526  0.0  0.1  13724  5352 ?        S    20:44   0:00 nginx: worker process
root       43546  0.0  0.0 221680  2252 pts/0    S+   20:47   0:00 grep --color=auto ngi
[root@nginx-node1 sbin]#
​
​
回滚完成,检测
[root@nginx-node1 ~]# curl -I 172.25.254.100
HTTP/1.1 200 OK
Server: nginx/1.24.0
Date: Thu, 15 Aug 2024 12:45:44 GMT
Content-Type: text/html
Content-Length: 615
Last-Modified: Thu, 15 Aug 2024 12:20:44 GMT
Connection: keep-alive
ETag: "66bdf29c-267"
Accept-Ranges: bytes

5.命令常用参数

[root@nginx-node1 sbin]# nginx -s stop
nginx: [error] invalid PID number "" in "/usr/local/nginx/logs/nginx.pid"
[root@nginx-node1 sbin]# ls
nginx  nginx.new  nginx.old
​
无法关闭。使用killall
[root@nginx-node1 sbin]# killall -9 nginx
[root@nginx-node1 sbin]# ls
nginx  nginx.new  nginx.old
[root@nginx-node1 sbin]# rm -fr nginx
[root@nginx-node1 sbin]# ls
nginx.new  nginx.old
[root@nginx-node1 sbin]# mv nginx.new nginx
[root@nginx-node1 sbin]# nginx
​
​
nginx -v/V 查看信息
​
查看版本
[root@nginx-node1 sbin]# nginx -v
nginx version: nginx/1.26.1
​
查看版本,编译参数等
[root@nginx-node1 sbin]# nginx -V
nginx version: nginx/1.26.1
built by gcc 11.3.1 20220421 (Red Hat 11.3.1-2) (GCC)
built with OpenSSL 3.0.1 14 Dec 2021
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --add-module=/root/echo-nginx-module-0.63 --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_gzip_static_module --with-http_stub_status_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module
​
​
nginx -t 检测配置文件语法是否正确
[root@nginx-node1 sbin]# 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
​
​
nginx -T 检测并打印
​
nginx -q 静默模式
​
nginx -s 指定信号
​
nginx -p 指定nginx目录
​
nginx -c  配置文件路径
​

nginx -g  开启nginx是指定配置
nginx必须关闭且配置文件注释,否则不成功
[root@nginx-node1 sbin]# nginx -s stop
[root@nginx-node1 sbin]# vim /usr/local/nginx/conf/nginx.conf
[root@nginx-node1 sbin]# nginx -g "worker_processes 6;"

6.nginx的服务启动编写

[root@nginx-node1 sbin]# vim /lib/systemd/system/nginx.service
[root@nginx-node1 sbin]# cat /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
PIDFile=/usr/local/nginx/logs/nginx.pid
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-node1 sbin]# systemctl daemon-reload
[root@nginx-node1 sbin]# nginx -s stop
[root@nginx-node1 sbin]# ps aux | grep nginx
root       43694  0.0  0.0 221680  2336 pts/0    S+   21:28   0:00 grep --color=auto nginx
[root@nginx-node1 sbin]# systemctl enable --now nginx
Created symlink /etc/systemd/system/multi-user.target.wants/nginx.service → /usr/lib/systemd/system/nginx.service.
[root@nginx-node1 sbin]# ps aux | grep nginx
root       43720  0.0  0.0   9872   944 ?        Ss   21:28   0:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx      43721  0.0  0.1  13772  4936 ?        S    21:28   0:00 nginx: worker process
root       43723  0.0  0.0 221680  2340 pts/0    S+   21:28   0:00 grep --color=auto nginx

三、Nginx核心配置

1.全局配置参数优化调整

[root@nginx-node1 sbin]# vim /usr/local/nginx/conf/nginx.conf

双核 01 10 四核0001 0010 0100 1000

修改pam限制

[root@nginx-node1 sbin]# vim /etc/security/limits.conf

[root@nginx-node1 sbin]# vim /usr/local/nginx/conf/nginx.conf

测试:

[root@nginx-node1 sbin]# dnf install httpd-tools -y
[root@nginx-node1 sbin]# ab -n 10000 -c 500 http://172.25.254.100/index.html
This is ApacheBench, Version 2.3 <$Revision: 1879490 $>
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 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.26.1
Server Hostname:        172.25.254.100
Server Port:            80
​
Document Path:          /index.html
Document Length:        615 bytes
​
Concurrency Level:      500
Time taken for tests:   0.510 seconds
Complete requests:      10000
Failed requests:        0
Total transferred:      8480000 bytes
HTML transferred:       6150000 bytes
Requests per second:    19592.44 [#/sec] (mean)
Time per request:       25.520 [ms] (mean)
Time per request:       0.051 [ms] (mean, across all concurrent requests)
Transfer rate:          16224.99 [Kbytes/sec] received
​
Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0   11   3.4     12      18
Processing:     3   13   4.1     14      29
Waiting:        0   10   3.8     10      26
Total:          9   25   5.4     27      37
​
Percentage of the requests served within a certain time (ms)
  50%     27
  66%     28
  75%     28
  80%     29
  90%     30
  95%     31
  98%     35
  99%     36
 100%     37 (longest request)

2.核心配置实例

2.1 新建PC web站点
[root@nginx-node1 sbin]# vim /usr/local/nginx/conf/nginx.conf
[root@nginx-node1 sbin]# mkdir -p /usr/local/nginx/conf.d
[root@nginx-node1 sbin]# vim ~/.vimrc
set ts=4 ai sw=4
[root@nginx-node1 sbin]# vim /usr/local/nginx/conf.d/vhost.conf
[root@nginx-node1 sbin]# cat /usr/local/nginx/conf.d/vhost.conf
server {
        listen 80;
        server_name www.wang.org;
        root /data/web/html;
        index index.html;
}
[root@nginx-node1 sbin]# mkdir -p /data/web/html
[root@nginx-node1 sbin]# echo www.wang.org > /data/web/html/index.html

[root@nginx-node1 sbin]# 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-node1 sbin]# nginx -s reload

[root@nginx-node1 sbin]# vim /usr/local/nginx/conf/nginx.conf

2.2 root

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

文件的绝对路径等于 root+location
/data/web/test1/


[root@nginx-node1 sbin]# vim /usr/local/nginx/conf.d/vhost.conf
server {
    listen 80;
    server_name www.wang.org;
    root /data/web/html;
    location /test1/ {
        root /data/web;
    }
}

[root@nginx-node1 sbin]# mkdir /data/web/test1 -p
[root@nginx-node1 sbin]# echo /data/web/test1 > /data/web/test1/index.html
[root@nginx-node1 sbin]# 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-node1 sbin]# nginx -s reload


有错查看日志
[root@nginx-node1 sbin]# tail /usr/local/nginx/logs/error.log

2.3 alias

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

alias中  认为/data/wewb/test1 的别名是 /test2
要么都不加斜杠  location /test2 {
                   alias /data/web/test1;
               }
要么都加斜杠    location /test2/ {
                   alias /data/web/test1/;
               }

location中使用root指令和alias指令的意义不同

root :给定的路径对应于location中的/uri左侧的/

alias :给定的路径对应于location中的/uri的完整路径

2.4 location的详细使用

在一个server中location配置段可存在多个,用于实现从uri到文件系统的路径映射;

ngnix会根据用户请求的URI来检查定义的所有location,按一定的优先级找出一个最佳匹配;

而后应用其配置在没有使用正则表达式的时候,nginx会先在server中的多个location选取匹配度最高的一个uri

uri是用户请求的字符串,即域名后面的web文件路径 然后使用该location模块中的正则url和字符串,如果匹配成功就结束搜索,并使用此location处理 此请求。

#语法规则:
location [ = | ~ | ~* | ^~ ] uri { ... }
=        #用于标准uri前,需要请求字串与uri精确匹配,大小敏感,如果匹配成功就停止向下匹配并立即处理请求

^~        #用于标准uri前,表示包含正则表达式,并且匹配以指定的正则表达式开头
          #对uri的最左边部分做匹配检查,不区分字符大小写
 
~         #用于标准uri前,表示包含正则表达式,并且区分大小写

~*        #用于标准uri前,表示包含正则表达式,并且不区分大写

不带符号   #匹配起始于此uri的所有的uri

\         #用于标准uri前,表示包含正则表达式并且转义字符。可以将 . * ?等转义为普通符号

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

目录优先级
[root@nginx-node1 ~]# vim /usr/local/nginx/conf.d/vhost.conf
server {
    listen 80;
    server_name www.wang.org;
    root /data/web/html;

    location /test {
        root /data/web1;
    }

    location = /test {
        root /data/web2;
    }

    location ^~ /t {
        root /data/web3;
    }

    location ~ .html$ {
        root /data/web4;
    }
    location ~* .HTML$ {
        root /data/web5;
    }
}


[root@nginx-node1 ~]# mkdir -p /data/web{1..5}/test
[root@nginx-node1 ~]# echo web1 > /data/web1/test/index.html
[root@nginx-node1 ~]# echo web2 > /data/web2/test/index.html
[root@nginx-node1 ~]# echo web3 > /data/web3/test/index.html
[root@nginx-node1 ~]# echo web4 > /data/web4/test/index.html
[root@nginx-node1 ~]# echo web5 > /data/web5/test/index.html
[root@nginx-node1 ~]# 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-node1 ~]# nginx -s reload

~/~*优先级相同,谁在前执行谁

  1. ~ 区分大小写

2.~* 不区分大小写

不带符号

^~ 以……开头

= 精确匹配 (不支持目录,必须指定文件)

由此可得

目录优先级 : ~/~* > 不带符号 > ^~ =(不支持目录)

文件优先级

文件优先级 : = > ~/~* > 不带符号 > ^~

3.Nginx账户认证功能

建立用户认证

[root@nginx-node1 ~]# htpasswd -cm /usr/local/nginx/.htpasswd admin
New password:                             #123456
Re-type new password:                     #123456
Adding password for user admin
[root@nginx-node1 ~]# cat /usr/local/nginx/.htpasswd
admin:$apr1$ACSVgR2Z$lA/CjDTPOdUVnlW8FPmAO.
[root@nginx-node1 ~]# htpasswd -m /usr/local/nginx/.htpasswd wang
New password:                              #123456
Re-type new password:                      #123456
Adding password for user wang
[root@nginx-node1 ~]# mkdir /data/web/wang
[root@nginx-node1 ~]# echo wang > /data/web/wang/index.html
[root@nginx-node1 ~]# vim /usr/local/nginx/conf.d/vhost.conf
server {
    listen 80;
    server_name www.wang.org;
    root /data/web/html;
    index index.html;

    location /wang {
        root /data/web;
    }
}
------------- 所有用户都可以登录 --------------

[root@nginx-node1 ~]# vim /usr/local/nginx/conf.d/vhost.conf
server {
    listen 80;
    server_name www.wang.org;
    root /data/web/html;
    index index.html;

    location /wang {
        root /data/web;
        auth_basic "login passwd !!";
        auth_basic_user_file "/usr/local/nginx/.htpasswd";
    }
}
------------ 需要输入用户名和密码登录 ----------------

[root@nginx-node1 ~]# nginx -s reload

需要输入用户名和密码登录

4.自定义错误页面

[root@nginx-node1 ~]# vim /usr/local/nginx/conf.d/vhost.conf
[root@nginx-node1 ~]# cat /usr/local/nginx/conf.d/vhost.conf
server {
        listen 80;
        server_name www.wang.org;
        root /data/web/html;
        index index.html;
        error_page 404 /40x.html;

        location /wang {
                root /data/web;
                auth_basic "login passwd !!";
                auth_basic_user_file "/usr/local/nginx/.htpasswd";
        }

        location = /40x.html {
                root /data/web/errorpage;
        }

}
[root@nginx-node1 ~]# mkdir -p /data/web/errorpage
[root@nginx-node1 ~]# echo error page > /data/web/errorpage/40x.html
[root@nginx-node1 ~]# nginx -s reload

当访问一个404错误页面时,进入40x.html的error page

5.自定义错误日志

server {
    listen 80;
    server_name www.wang.org;
    root /data/web/html;
    index index.html;
    error_page 404 /40x.html;
    error_log /var/log/wang.org/error.log;
    access_log /var/log/wang.org/access.log;

    location /wang {
        root /data/web;
        auth_basic "login passwd !!";
        auth_basic_user_file "/usr/local/nginx/.htpasswd";
    }

    location = /40x.html {
        root /data/web/errorpage;
    }

}

[root@nginx-node1 ~]# mkdir /var/log/wang.org
[root@nginx-node1 ~]# nginx -s reload

本地解析:vim /etc/hosts
[root@nginx-node1 ~]# curl www.wang.org
www.wang.org
[root@nginx-node1 ~]# cat /var/log/wang.org/access.log
172.25.254.1 - - [16/Aug/2024:14:41:08 +0800] "GET / HTTP/1.1" 200 13 "-" "curl/8.4.0"
172.25.254.1 - - [16/Aug/2024:14:41:20 +0800] "GET / HTTP/1.1" 200 13 "-" "curl/8.4.0"
172.25.254.1 - - [16/Aug/2024:14:42:29 +0800] "GET /aa HTTP/1.1" 200 13 "-" "curl/8.4.0"
[root@nginx-node1 ~]#curl www.wang.org/aa
errordafault

6.检测文件是否存在

server {
    listen 80;
    server_name www.wang.org;
    root /data/web/html;
    index index.html;
    error_page 404 /40x.html;
    error_log /var/log/wang.org/error.log;
    access_log /var/log/wang.org/access.log;
    try_files $uri $uri.html $uri/index.html /error/default.html;

    location /wang {
        root /data/web;
        auth_basic "login passwd !!";
        auth_basic_user_file "/usr/local/nginx/.htpasswd";
    }

    location = /40x.html {
        root /data/web/errorpage;
    }

}

[root@nginx-node1 ~]# mkdir /data/web/html/error
[root@nginx-node1 ~]# echo error default > /data/web/html/error/index.html

检测
[root@nginx-node1 ~]# curl www.wang.org
www.wang.org

7. 长连接配置

检测工具
[root@nginx-node1 ~]# dnf install telnet -y

[root@nginx-node1 ~]# telnet www.wang.org 80
Trying 172.25.254.100...
Connected to www.wang.org.
Escape character is '^]'.
GET / HTTP/1.1
HOST: www.wang.org

HTTP/1.1 200 OK
Server: nginx/1.26.1
Date: Fri, 16 Aug 2024 07:05:47 GMT
Content-Type: text/html
Content-Length: 13
Last-Modified: Thu, 15 Aug 2024 14:56:49 GMT
Connection: keep-alive
Keep-Alive: timeout=60
ETag: "66be1731-d"
Accept-Ranges: bytes

www.wang.org

8.作为下载服务器配置

autoindex on | off;            #自动文件索引功能,默为off
autoindex_exact_size on | off; #计算文件确切大小(单位bytes),off 显示大概大小(单位K、M),默认on
autoindex_localtime on | off ; #显示本机时间而非GMT(格林威治)时间,默认off
autoindex_format html | xml | json | jsonp; #显示索引的页面文件风格,默认html
limit_rate rate; #限制响应客户端传输速率(除GET和HEAD以外的所有方法),单位
B/s,bytes/second, #默认值0,表示无限制,此指令由
ngx_http_core_module提供
set $limit_rate 4k; #也可以通变量限速,单位B/s,同时设置,此项优级高.

[root@nginx-node1 ~]# vim /usr/local/nginx/conf.d/vhost.conf

location /download {
        root /data/web;
        autoindex on;
        autoindex_location on;
        autoindex_exact_size off;
        limit_rate 1024;
    }

[root@nginx-node1 ~]# mkdir -p /data/web/download
[root@nginx-node1 ~]# dd if=/dev/zero of=/data/web/download/wanglife bs=1M count=100
记录了100+0 的读入
记录了100+0 的写出
104857600字节(105 MB,100 MiB)已复制,0.0344068 s,3.0 GB/s
[root@nginx-node1 ~]# nginx -s reload

四、Nginx高级配置

4.1 Nginx状态页

[root@nginx-node1 ~]# vim /usr/local/nginx/conf.d/status.conf
server {
    listen 80;
    server_name status.wang.org;
    root /data/web/html;
    index index.html;

    location /status {
        stub_status;
        #allow 127.0.0.1;
        #deny all;
        auth_basic "login";
        auth_basic_user_file "/usr/local/nginx/.htpasswd";
    }
}
[root@nginx-node1 ~]# nginx -s reload

4.2Nginx压缩功能

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

#启用或禁用gzip压缩,默认关闭
gzip on | off; 

#压缩比由低到高从1到9,默认为1,值越高压缩后文件越小,但是消耗cpu比较高。基本设定未4或者5
gzip_comp_level 4;

#gzip压缩的最小文件,小于设置值的文件将不会压缩
gzip_min_length 1k; 

#启用压缩功能时,协议的最小版本,默认HTTP/1.1
gzip_http_version 1.0 | 1.1;

#如果启用压缩,是否在响应报文首部插入“Vary: Accept-Encoding”,一般建议打开
gzip_vary on | off; 

[root@nginx-node1 ~]# vim /usr/local/nginx/conf/nginx.conf

[root@nginx-node1 ~]# 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-node1 ~]# nginx -s reload
[root@nginx-node1 ~]# cat /usr/local/nginx/logs/access.log > /data/web/html/big.html

测试小于1k的文件是否会压缩
[root@nginx-node1 ~]# curl --head --compressed 172.25.254.100/small.html
HTTP/1.1 200 OK
Server: nginx/1.26.1
Date: Fri, 16 Aug 2024 08:15:44 GMT
Content-Type: text/html
Content-Length: 11
Last-Modified: Fri, 16 Aug 2024 08:11:14 GMT
Connection: keep-alive
Keep-Alive: timeout=60
ETag: "66bf09a2-b"
Accept-Ranges: bytes

[root@nginx-node1 ~]# curl --head --compressed 172.25.254.100/big.html
HTTP/1.1 200 OK
Server: nginx/1.26.1
Date: Fri, 16 Aug 2024 08:15:59 GMT
Content-Type: text/html
Last-Modified: Fri, 16 Aug 2024 08:15:11 GMT
Connection: keep-alive
Keep-Alive: timeout=60
Vary: Accept-Encoding
ETag: W/"66bf0a8f-10a13a"
Content-Encoding: gzip

[root@nginx-node1 ~]# curl --compressed 172.25.254.100/big.html
172.25.254.1 - - [15/Aug/2024:20:41:25 +0800] "GET / HTTP/1.1" 200 615 "-" "curl/8.4.0"
172.25.254.1 - - [15/Aug/2024:20:41:26 +0800] "GET / HTTP/1.1" 200 615 "-" "curl/8.4.0"
172.25.254.1 - - [15/Aug/2024:20:41:27 +0800] "GET / HTTP/1.1" 200 615 "-" "curl/8.4.0"
172.25.254.1 - - [15/Aug/2024:20:41:30 +0800] "GET / HTTP/1.1" 200 615 "-" "curl/8.4.0"
172.25.254.1 - - [15/Aug/2024:20:41:31 +0800] "GET / HTTP/1.1" 200 615 "-" "curl/8.4.0"
172.25.254.1 - - [15/Aug/2024:20:41:32 +0800] "GET / HTTP/1.1" 200 615 "-" "curl/8.4.0"
172.25.254.1 - - [15/Aug/2024:20:41:33 +0800] "GET / HTTP/1.1" 200 615 "-" "curl/8.4.0"

[root@nginx-node1 ~]# curl --head --compressed 172.25.254.100/big.html
HTTP/1.1 200 OK
Server: nginx/1.26.1
Date: Fri, 16 Aug 2024 08:16:21 GMT
Content-Type: text/html
Last-Modified: Fri, 16 Aug 2024 08:15:11 GMT
Connection: keep-alive
Keep-Alive: timeout=60
Vary: Accept-Encoding
ETag: W/"66bf0a8f-10a13a"
Content-Encoding: gzip

[root@nginx-node1 ~]# curl --head --compressed 172.25.254.100/small.html
HTTP/1.1 200 OK
Server: nginx/1.26.1
Date: Fri, 16 Aug 2024 08:16:24 GMT
Content-Type: text/html
Content-Length: 11
Last-Modified: Fri, 16 Aug 2024 08:11:14 GMT
Connection: keep-alive
Keep-Alive: timeout=60
ETag: "66bf09a2-b"
Accept-Ranges: bytes
[root@nginx-node1 ~]# du -sh /data/web/html/small.html
4.0K    /data/web/html/small.html
[root@nginx-node1 ~]# du -sh /data/web/html/big.html
1.1M    /data/web/html/big.html
[root@nginx-node1 ~]#

不会自己压缩,在发送过程中压缩

4.3Nginx变量

4.3.1 内置变量

编译之前必须加入echo,否则无法执行

[root@nginx-node1 ~]# cd /usr/local/nginx/conf.d
[root@nginx-node1 conf.d]# vim vars.conf
server {
    listen 80;
    server_name var.wang.org;
    root /data/web/html;
    index index.html;

    location /var {
        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 $http_cookie;
        echo $cookie_key2;
    }
}

重启
[root@nginx-node1 conf.d]# nginx -s reload

本地解析
[root@nginx-node1 conf.d]# vim /etc/hosts

访问测试
[root@nginx-node1 conf.d]# curl -b "key1=wang,key2=wang1" -u wang:wang var.wang.org/var?name=wang&&id=6666
测试结果
172.25.254.100
name=wang
?
/data/web/html
/var
var.wang.org
40618
wang
GET
/data/web/html/var
/var?name=wang
http
HTTP/1.1
172.25.254.100
var.wang.org
80
curl/7.76.1
key1=wang,key2=wang1      #cookie信息
wang1

4.3.2 自定义变量
[root@nginx-node1 conf.d]# vim vars.conf
server {
    listen 80;
    server_name var.wang.org;
    root /data/web/html;
    index index.html;

    location /var {
        default_type text/html;
        set $wang wang;
        echo $wang;
    }
}

重启
[root@nginx-node1 conf.d]# nginx -s reload

访问测试
[root@nginx-node1 conf.d]# curl  -u wang:wang var.wang.org/var?name=wang&&id=6666
172.25.254.100
name=wang
?
/data/web/html
/var
var.wang.org
40618     
wang

五、Nginx Rewrite

5.1 ngx_http_rewrite_module模块指令

官方文档: Module ngx_http_rewrite_module

5.1.1 if指令

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

server {
    listen 80;
    server_name var.wang.org;
    root /data/web/html;
    index index.html;

    location /test2 {
      if ( !-e $request_filename ){
        echo "$request_filename is not exist";
      }
    }
}

[root@nginx-node1 conf.d]# nginx -s reload

检测
[root@nginx-node1 conf.d]# curl var.wang.org/test2/index.html
/data/web/html/test2/index.html is not exist

5.1.1 berak

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

server {
    listen 80;
    server_name var.wang.org;
    root /data/web/html;
    index index.html;

    location /break {
        default_type text/html;
        set $name wang;
        echo $name;
        if ( $http_user_agent = "curl/7.76.1" ){
            break;
        }
        set $id 666;
        echo $id;
    }
}

[root@nginx-node1 conf.d]# nginx -s reload

检测
[root@nginx-node1 conf.d]# curl var.wang.org/break
wang

[root@nginx-node1 conf.d]# curl -A "firefox"    var.wang.org/break                 -A指定浏览器
wang
666

5.1.1 return

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

server {
    listen 80;
    server_name var.wang.org;
    root /data/web/html;
    index index.html;

location /return {
        default_type text/html;
        if ( !-e $request_filename){
            return 301 http://www.baidu.com;
        }
        echo "$request_filename is exist";
    }
}

[root@nginx-node1 conf.d]# nginx -s reload

[root@nginx-node1 conf.d]# curl -I var.wang.org/return
HTTP/1.1 301 Moved Permanently
Server: nginx/1.26.1
Date: Sun, 18 Aug 2024 03:48:45 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive
Keep-Alive: timeout=60
Location: http://www.baidu.com

[root@nginx-node1 conf.d]# mkdir -p /data/web/html/return
[root@nginx-node1 conf.d]# curl -I var.wang.org/return
HTTP/1.1 200 OK
Server: nginx/1.26.1
Date: Sun, 18 Aug 2024 03:49:09 GMT
Content-Type: text/html
Connection: keep-alive
Keep-Alive: timeout=60
Vary: Accept-Encoding

5.2 rewrite指令

5.2.1 rewrite flag

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

跳转型指由客户端浏览器重新对新地址进行请求

代理型是在WEB服务器内部实现跳转

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

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

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

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

redirect 和 permanet

permanet 永久重定向301

域名永久型调整,即域名永远跳转至另外一个新的域名,之前的域名再也不使用,跳转记录可以缓存到 客户端浏览器

永久重定向会缓存DNS解析记录, 浏览器中有 from disk cache 信息,即使nginx服务器无法访问,浏览器也 会利用缓存进行重定向

[root@nginx-node1 conf.d]# vim vars.conf
server {
    listen 80;
    server_name var.wang.org;
    root /data/web/html;
    index index.html;

    location / {
        root /data/web/var;
        index index.html;
        rewrite / http://www.wang.com permanent;
        #rewrite / http://www.wang.com redirect;
    }
}


[root@nginx-node1 conf.d]# nginx -s reload

检测
[root@nginx-node1 conf.d]# curl -I var.wang.org
HTTP/1.1 301 Moved Permanently
Server: nginx/1.26.1
Date: Sun, 18 Aug 2024 03:50:43 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive
Keep-Alive: timeout=60
Location: http://www.wang.com

redirect 临时重定向302

域名临时重定向,告诉浏览器域名不是固定重定向到当前目标域名,后期可能随时会更改,因此浏览器 不会缓存当前域名的解析记录,而浏览器会缓存永久重定向的DNS解析记录,这也是临时重定向与永久 重定向最大的本质区别。

即当nginx服务器无法访问时,浏览器不能利用缓存,而导致重定向失败

[root@nginx-node1 conf.d]# vim vars.conf
server {
    listen 80;
    server_name var.wang.org;
    root /data/web/html;
    index index.html;

    location / {
        root /data/web/var;
        index index.html;
        #rewrite / http://www.wang.com permanent;
        rewrite / http://www.wang.com redirect;
    }
}


[root@nginx-node1 conf.d]# nginx -s reload

检测
[root@nginx-node1 conf.d]# curl -I var.wang.org
HTTP/1.1 302 Moved Temporarily
Server: nginx/1.26.1
Date: Sun, 18 Aug 2024 04:13:38 GMT
Content-Type: text/html
Content-Length: 145
Connection: keep-alive
Keep-Alive: timeout=60
Location: http://www.wang.com

break 和 last
[root@nginx-node1 conf.d]#  mkdir  /data/web/html/{test1,test2,break,last} -p
[root@nginx-node1 conf.d]# echo test1 > /data/web/html/test1/index.html
[root@nginx-node1 conf.d]# echo test2 > /data/web/html/test2/index.html
[root@nginx-node1 conf.d]# echo last > /data/web/html/last/index.html
[root@nginx-node1 conf.d]# echo break > /data/web/html/break/index.html

[root@nginx-node1 conf.d]# vim vars.conf
server {
    listen 80;
    server_name var.wang.org;
    root /data/web/html;
    index index.html;

    location /break {              #执行在当前location中的test1
        root /data/web/html;       #并停止
        rewrite ^/break/(.*) /test1/$1 break;
        rewrite ^/test1/(.*) /test2/$1;
    }

    location /last {      #执行下面的location,并停止,不执行test2
        root /data/web/html;
        rewrite ^/last/(.*) /test1/$1 last;
        rewrite ^/test1/(.*) /test2/$1;
    }

    location /test1 {
        root /data/web/html;
        return 666 "hahahahahahhahhahaa";
    }

     location /test2 {
        root /data/web/html;
	}
}

5.2.2 rewrite自动跳转https

基于通信安全考虑公司网站要求全站 https,因此要求将在不影响用户请求的情况下将http请求全 部自动跳转至 https,另外也可以实现部分 location 跳转

全站加密

[root@nginx-node1 ~]# cd /usr/local/nginx/
[root@nginx-node1 nginx]# mkdir certs
[root@nginx-node1 nginx]# openssl req  -newkey  rsa:2048 -nodes -sha256 -keyout /usr/local/nginx/certs/wang.org.key -x509  -days 365 -out /usr/local/nginx/certs/wang.org.crt
[root@nginx-node1 nginx]# vim /usr/local/nginx/conf.d/vhost.conf
server {
    listen 80;
    listen 443 ssl;
    server_name www.wang.org;
    root /data/web/html;
    index index.html;
    ssl_certificate /usr/local/nginx/certs/wang.org.crt;
    ssl_certificate_key /usr/local/nginx/certs/wang.org.key;
    ssl_session_cache    shared:SSL:1m;
    ssl_session_timeout  5m;

    location / {
        if ( $scheme = http ){
            rewrite / https://$host redirect;
        }
    }
}
[root@nginx-node1 conf.d]# nginx -s reload


检测
[root@nginx-node1 conf.d]# curl -L www.wang.org
curl: (60) SSL certificate problem: self-signed certificate
More details here: https://curl.se/docs/sslcerts.html

curl failed to verify the legitimacy of the server and therefore could not
establish a secure connection to it. To learn more about this situation and
how to fix it, please visit the web page mentioned above.
[root@nginx-node1 conf.d]# curl -kL www.wang.org
www.wang.org
[root@nginx-node1 conf.d]# curl -I www.wang.org
HTTP/1.1 302 Moved Temporarily
Server: nginx/1.26.1
Date: Sun, 18 Aug 2024 13:01:08 GMT
Content-Type: text/html
Content-Length: 145
Connection: keep-alive
Keep-Alive: timeout=60
Location: https://www.wang.org

5.2.3 判断文件是否存在

页面不存在404报错

[root@nginx-node1 conf.d]# vim vhost.confserver {
    listen 80;
    listen 443 ssl;
    server_name www.wang.org;
    root /data/web/html;
    index index.html;
    ssl_certificate /usr/local/nginx/certs/wang.org.crt;
    ssl_certificate_key /usr/local/nginx/certs/wang.org.key;
    ssl_session_cache    shared:SSL:1m;
    ssl_session_timeout  5m;

    location / {
        if ( $scheme = http ){
            rewrite /(.*) https://$host/$1 redirect;
        }

        if ( !-e $request_filename ){
            rewrite /(.*) https://$host/index.html redirect;
        }
    }
}

[root@nginx-node1 conf.d]# nginx -s reload

访问时输入了一个错误的URL,可以将用户重定向至官网首页

存在的页面,正确显示

5.3Nginx防盗链

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

none:        #请求报文首部没有referer首部,
              #比如用户直接在浏览器输入域名访问web网站,就没有referer信息。

blocked:      #请求报文有referer首部,但无有效值,比如为空。

server_names: #referer首部中包含本主机名及即nginx 监听的server_name。

arbitrary_string: #自定义指定字符串,但可使用*作通配符。示例: *.timinglee.org  www.timinglee.*

regular expression: #被指定的正则表达式模式匹配到的字符串,要使用~开头,例如:~.*\.timinglee\.com

5.3.1 实现盗链

在一个web 站点盗链另一个站点的资源信息,比如:图片、视频等

正常访问自己站点图片

盗链

#新建一个主机172.25.254.10,盗取另一台主机www.wang.org/images/zhomian.png的图片

[root@node2 ~]#dnf install httpd -y
[root@node2 ~]#echo 172.25.24.10 > /var/www/html/index.html
[root@node2 ~]# cd /var/www/html
[root@node2 html]# ls
index.html

#盗链web页面
[root@node2 html]# vim index.html
<html>
  <head>
    <meta http-equiv=Content-Type content="text/html;charset=utf-8">
    <title>盗链</title>
</head>
  <body>
    <img src="http://www.wang.org/images/zhuomian.png" >
    <h1 style="color:red">欢迎大家</h1>
    <p><a href=http://www.wang.org>狂点狂点</a>出门见喜</p>
  </body>
</html>

[root@node2 html]# systemctl restart httpd

5.3.2实现防盗链

基于访问安全考虑,nginx支持通过ngx_http_referer_module模块,检查访问请求的referer信息是否有效 实现防盗链功能

location /images  {
        valid_referers none blocked server_names *.wang.org ~/.baidu/.;
        if ( $invalid_referer ){
                return 404;
        }

    }

全站禁止访问
location /  {
        valid_referers none blocked server_names *.wang.org ~/.baidu/.;
        if ( $invalid_referer ){
                return 404;
        }

    }

 location /images  {
        valid_referers none blocked server_names *.wang.org ~/.baidu/.;
        if ( $invalid_referer ){
                rewrite ^/   http://www.wang.org/daolian.png;
        }

    }

六、Nginx反向代理功能

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

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

ngx_http_proxy_module: #将客户端的请求以http协议转发至指定服务器进行处理
ngx_http_upstream_module #用于定义为proxy_pass,fastcgi_pass,uwsgi_pass
#等指令引用的后端服务器分组
ngx_stream_proxy_module: #将客户端的请求以tcp协议转发至指定服务器处理
ngx_http_fastcgi_module: #将客户端对php的请求以fastcgi协议转发至指定服务器助理
ngx_http_uwsgi_module: #将客户端对Python的请求以uwsgi协议转发至指定服务器处理

6.1实现http反向代理

6.1.1 反向代理参数
proxy_pass; #用来设置将客户端请求转发给的后端服务器的主机
            #可以是主机名(将转发至后端服务做为主机头首部)、IP地址:端口的方式
            #也可以代理到预先设置的主机群组,需要模块ngx_http_upstream_module支持

#如果location定义其uri时使用了正则表达式模式(包括~,~*,但不包括^~),则proxy_pass之后必须不能
使用uri
#即不能有/ ,用户请求时传递的uri将直接附加至后端服务器之后
server {
...
server_name HOSTNAME;
location ~|~* /uri/ {
proxy_pass http://host:port; #proxy_pass后面的url 不能加/
}
...
}
http://HOSTNAME/uri/ --> http://host/uri/

proxy_hide_header field; #用于nginx作为反向代理的时候
                         #在返回给客户端http响应时
			 #隐藏后端服务器相应头部的信息
 			 #可以设置在http,server或location块

proxy_pass_header field; #透传
                         #默认nginx在响应报文中不传递后端服务器的首部字段Date, Server, X-Pad, X-Accel等参数
                         #如果要传递的话则要使用 proxy_pass_header field声明将后端服务器返回的值传递给客户端
                         #field 首部字段大小不敏感

proxy_pass_request_body on | off;
#是否向后端服务器发送HTTP实体部分,可以设置在http,server或location块,默认即为开启

proxy_pass_request_headers on | off;
#是否将客户端的请求头部转发给后端服务器,可以设置在http,server或location块,默认即为开启

proxy_set_header;
6.1.1.2 实战案例: 反向代理单台 web 服务器
要求:将用户对域 www.timinglee.org 的请求转发给后端服务器处理
#可更改或添加客户端的请求头部信息内容并转发至后端服务器,比如在后端服务器想要获取客户端的真实IP的
时候,就要更改每一个报文的头部

proxy_connect_timeout time;
#配置nginx服务器与后端服务器尝试建立连接的超时时间,默认为60秒
用法如下:proxy_connect_timeout 6s;
#60s为自定义nginx与后端服务器建立连接的超时时间,超时会返回客户端504响应码

proxy_read_timeout time;
#配置nginx服务器向后端服务器或服务器组发起read请求后,等待的超时时间,默认60s

proxy_send_timeout time;
#配置nginx项后端服务器或服务器组发起write请求后,等待的超时 时间,默认60s

proxy_http_version 1.0;
#用于设置nginx提供代理服务的HTTP协议的版本,默认http 1.0

proxy_ignore_client_abort off;
#当客户端网络中断请求时,nginx服务器中断其对后端服务器的请求。即如果此项设置为on开启,则服务器、
会忽略客户端中断并一直等着代理服务执行返回,如果设置为off,则客户端中断后Nginx也会中断客户端请求
并立即记录499日志,默认为off

6.1.2反向代理单台 web 服务器
#新建两台主机172.25.254.10/172.25.254.20
[root@web20 ~]# echo 172.25.254.20 > /var/www/html/index.html
[root@web20 ~]# systemctl enable --now httpd
Created symlink /etc/systemd/system/multi-user.target.wants/httpd.service → /usr/lib/systemd/system/httpd.service.

[root@web10 ~]# echo 172.25.254.10 > /var/www/html/index.html
[root@web10 ~]# systemctl enable --now httpd
Created symlink /etc/systemd/system/multi-user.target.wants/httpd.service → /usr/lib/systemd/system/httpd.service.

#172.25.254.100
[root@nginx-node1 conf.d]# curl 172.25.254.20
172.25.254.20
[root@nginx-node1 conf.d]# curl 172.25.254.10
172.25.254.10
[root@nginx-node1 conf.d]# vim vhost.conf
server {
    listen 80;
    server_name www.wang.org;

    location / {
        proxy_pass http://172.25.254.10:80;
    }
}

#web20主机中修改监听端口
[root@web20 ~]# vim /etc/httpd/conf/httpd.conf
[root@web20 ~]# systemctl restart httpd
[root@web20 ~]# mkdir -p /var/www/html/static
[root@web20 ~]# echo 172.25.254.20 static  > /var/www/html/static/index.html


[root@nginx-node1 conf.d]# vim vhost.conf
server {
    listen 80;
    server_name www.wang.org;

    location / {
        proxy_pass http://172.25.254.10:80;
    }

    location /static {
        proxy_pass http://172.25.254.20:8080;
    }
}
[root@nginx-node1 conf.d]# nginx -s reload

6.1.3动静分离
[root@nginx-node1 conf.d]# vim vhost.conf
server {
    listen 80;
    server_name www.wang.org;

    location  ~ \.php$  {
        proxy_pass http://172.25.254.10:80;
    }

    location /static {
        proxy_pass http://172.25.254.20:8080;
    }
}
[root@nginx-node1 conf.d]# nginx -s reload


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

6.1.4 反向代理:缓存功能

缓存功能默认关闭状态,需要先动配置才能启用

proxy_cache zone_name | off; 默认off
#指明调用的缓存,或关闭缓存机制;Context:http, server, location
#zone_name 表示缓存的名称.需要由proxy_cache_path事先定义

proxy_cache_key string;
#缓存中用于“键”的内容,默认值:proxy_cache_key $scheme$proxy_host$request_uri;


proxy_cache_valid [code ...] time;
#定义对特定响应码的响应内容的缓存时长,定义在http{...}中

#示例:在http配置定义缓存信息
proxy_cache_path /var/cache/nginx/proxy_cache #定义缓存保存路径,proxy_cache会自动创建
levels=1:2:2 #定义缓存目录结构层次
#1:2:2可以生成
2^4x2^8x2^8=2^20=1048576个目录
keys_zone=proxycache:20m #指内存中缓存的大小,主要用于存放key和metadata
(如:使用次数)
#一般1M可存放8000个左右的key
inactive=120s #缓存有效时间
max_size=10g; #最大磁盘占用空间,磁盘存入文件内容的缓存空间最大值

1.压测

[root@web10 ~]# ab -n1000 -c100 Web Page Under Construction

2.缓存配置
[root@nginx-node1 conf.d]# 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;               #配置在nginx.conf http配置段

[root@nginx-node1 conf.d]# vim vhost.conf
server {
    listen 80;
    server_name www.wang.org;

    location ~ \.php$  {
        proxy_pass http://172.25.254.10:80;
    }

    location /static {
        proxy_pass http://172.25.254.20:8080;
        proxy_cache proxycache;
        proxy_cache_key $request_uri;
        proxy_cache_valid 200 302 301 10m;
        proxy_cache_valid any 1m;
    }
}

3.访问并验证缓存文件

6.1.5 http反向代理负载均衡(七层)
1. http upstream配置参数
#server支持的parameters如下:
weight=number #设置权重,默认为1,实现类似于LVS中的WRR,WLC等

max_conns=number #给当前后端server设置最大活动链接数,默认为0表示没有限制

max_fails=number #后端服务器的下线条件,当客户端访问时,对本次调度选中的后端服务器连续进行检测多少次,如果都失败就标记为不可用,默认为1次,当客户端访问时,才会利用TCP触发对探测后端服务器健康性检查,而非周期性的探测

fail_timeout=time #后端服务器的上线条件,对已经检测到处于不可用的后端服务器,每隔此时间间隔再次进行检测是否恢复可用,如果发现可用,则将后端服务器参与调度,默认为10秒

backup #设置为备份服务器,当所有后端服务器不可用时,才会启用此备用服务器


down #标记为down状态,可以平滑下线后端服务器

resolve #当server定义的是主机名的时候,当A记录发生变化会自动应用新IP而不用重启Nginx

2.后端多台 web服务器
#部署apache服务器
[root@web20 ~]# yum install httpd -y
[root@web20 ~]# echo 172.25.254.20 > /var/www/html/index.html
[root@web20 ~]# systemctl enable --now httpd

[root@web10 ~]# yum install httpd -y
[root@web10 ~]# echo 172.25.254.10 >> /var/www/html/index.html
[root@web10 ~]# systemctl enable --now httpd

#访问测试
[root@nginx-node1 ~]# curl http://172.25.254.10
172.25.254.10
[root@nginx-node1 ~]# curl http://172.25.254.20
 172.25.254.20
 
 
 #nginx反向代理
 [root@nginx-node1 conf.d]# vim vhost.conf
 upstream webcluster {
    server 172.25.254.10:80 fail_timeout=15s max_fails=3;
    server 172.25.254.20:8080 fail_timeout=15s max_fails=3;
    server 172.25.254.100:80 backup;
}

server {
    listen 80;
    server_name www.wang.org;

    location / {
        proxy_pass http://webcluster;
    }
}
[root@nginx-node1 conf.d]# nginx -s reload

默认轮询

ip_hash

ip_hash不能加backup

测试

uri

#hash $request_uri consistent;

[root@web10 ~]# mkdir -p /var/www/html/static [root@web10 ~]# echo 172.25.254.10 static > /var/www/html/static/index.html

cookie

hash $cookie_wang;

加cookie前,轮询

加cookie后

​​​​​​​[root@nginx-node1 conf.d]# vim vhost.conf
upstream webcluster {
    #ip_hash;
    #hash $request_uri consistent;
    hash $cookie_wang;
    server 172.25.254.10:80 fail_timeout=15s max_fails=3;
    server 172.25.254.20:8080 fail_timeout=15s max_fails=3;
    #server 172.25.254.100:80 backup;
}

server {
    listen 80;
    server_name www.wang.org;

    location / {
        proxy_pass http://webcluster;
    }


}

6.2 Nginx四层负载均衡

tcp负载均衡参数

tcp的负载均衡要写在http语句块之外

stream { #定义stream相关的服务;
Context:main
upstream backend { #定义后端服务器
hash $remote_addr consistent; #定义调度算法
server backend1.example.com:12345 weight=5; #定义具体server
server 127.0.0.1:12345 max_fails=3 fail_timeout=30s;
server unix:/tmp/backend3;
}
upstream dns { #定义后端服务器
server 10.0.0.1:53; #定义具体server
server dns.example.com:53;
}
server { #定义server
listen 12345; #监听IP:PORT
proxy_connect_timeout 1s; #连接超时时间
proxy_timeout 3s; #转发超时时间
proxy_pass backend; #转发到具体服务器组
}
server {
listen 127.0.0.1:53 udp reuseport;
proxy_timeout 20s;
proxy_pass dns;
}
server {
listen [::1]:12345;
proxy_pass unix:/tmp/stream.socket;
}
}

1.dns
[root@web20 ~]# dnf install bind -y
[root@web20 ~]# vim /etc/named.conf
[root@web20 ~]# vim /etc/named.rfc1912.zones
[root@web20 ~]# cd /var/named
[root@web20 named]# cp named.localhost wang.org.zone -p
[root@web20 named]# vim wang.org.zone
[root@web20 named]# systemctl restart named
[root@web20 named]# dig www.wang.org @172.25.254.20
; <<>> DiG 9.16.23-RH <<>> www.wang.org @172.25.254.20
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 24680
;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 1232
; COOKIE: 69777cc7879620870100000066c2148b69bfc4921fea2d5f (good)
;; QUESTION SECTION:
;www.wang.org.                  IN      A

;; ANSWER SECTION:
www.wang.org.           86400   IN      A       172.25.254.20

;; Query time: 2 msec
;; SERVER: 172.25.254.20#53(172.25.254.20)
;; WHEN: Sun Aug 18 23:34:35 CST 2024
;; MSG SIZE  rcvd: 85

#另一台主机直接复制
[root@web20 named]# scp -p /etc/named.{conf,rfc1912.zones} root@172.25.254.10:/etc
The authenticity of host '172.25.254.10 (172.25.254.10)' can't be established.
ED25519 key fingerprint is SHA256:dI2jEBtwZxvIn4aH5IS7HrNjAEEO+88WNj1+mNP744U.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '172.25.254.10' (ED25519) to the list of known hosts.
root@172.25.254.10's password:
named.conf                                            100% 1727     2.3MB/s   00:00
named.rfc1912.zones                                   100% 1116     4.5MB/s   00:00
[root@web20 named]# scp -p /var/named/wang.org.zone root@172.25.254.10:/var/named/wang.org.zone
root@172.25.254.10's password:
wang.org.zone                                         100%  191   620.9KB/s   00:00


[root@web10 ~]# cd /var/named/
[root@web10 named]# ll
-rw-r----- 1 root  root   191  8月 18 23:39 wang.org.zone
[root@web10 named]# chgrp named  wang.org.zone
[root@web10 named]# ll
-rw-r----- 1 root  named  191  8月 18 23:39 wang.org.zone
[root@web10 named]# systemctl restart named
[root@web10 named]# dig www.wang.org @172.25.254.10

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

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 1232
; COOKIE: fc521ca223e34e0c0100000066c21626414786ab2fc7b833 (good)
;; QUESTION SECTION:
;www.wang.org.                  IN      A

;; ANSWER SECTION:
www.wang.org.           86400   IN      A       172.25.254.10

;; Query time: 0 msec
;; SERVER: 172.25.254.10#53(172.25.254.10)
;; WHEN: Sun Aug 18 23:41:26 CST 2024
;; MSG SIZE  rcvd: 85

[root@web20 named]# vim /etc/named.conf

[root@web20 named]# vim /etc/named.rfc1912.zones

[root@web20 named]# vim wang.org.zone

[root@nginx-node1 conf.d]# vim vhost.conf

upstream webcluster {
    #ip_hash;
    #hash $request_uri consistent;
    hash $cookie_wang;
    server 172.25.254.10:80 fail_timeout=15s max_fails=3;
    server 172.25.254.20:8080 fail_timeout=15s max_fails=3;
    #server 172.25.254.100:80 backup;
}

server {
    listen 80;
    server_name www.wang.org;

    location / {
        proxy_pass http://webcluster;
    }


}

[root@nginx-node1 conf.d]# vim /usr/local/nginx/conf/nginx.conf
include "/usr/local/nginx/tcpconf.d/*.conf";
#如上图所示

[root@nginx-node1 conf.d]# mkdir -p /usr/local/nginx/tcpconf.d
[root@nginx-node1 conf.d]# ls
status.conf  vars.conf  vhost.conf
[root@nginx-node1 conf.d]# vim dns.conf
stream {

    upstream dns {
        server 172.25.254.10:53 fail_timeout=15s max_fails=3;
        server 172.25.254.20:53 fail_timeout=15s max_fails=3;
    }

    server {
        listen 53 udp reuseport;
        proxy_timeout 20s;
        proxy_pass dns;
    }
}


[root@nginx-node1 conf.d]# mv dns.conf /usr/local/nginx/tcpconf.d/
[root@nginx-node1 conf.d]# ls
status.conf  vars.conf  vhost.conf
[root@nginx-node1 conf.d]# cd /usr/local/nginx/tcpconf.d
[root@nginx-node1 tcpconf.d]# ls
dns.conf
[root@nginx-node1 tcpconf.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-node1 tcpconf.d]# nginx -s reload
[root@nginx-node1 tcpconf.d]# netstat -antlupe | grep 53
udp        0      0 0.0.0.0:53              0.0.0.0:*                           0          67764      2744/nginx: master
udp        0      0 0.0.0.0:53              0.0.0.0:*                           0          67763      2744/nginx: master
udp        0      0 0.0.0.0:5353            0.0.0.0:*                           70         17349      891/avahi-daemon: r
udp6       0      0 :::5353                 :::*                                70         17350      891/avahi-daemon: r

[root@nginx-node1 tcpconf.d]# dig www.wang.org @172.25.254.100

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

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 1232
; COOKIE: 25dccc21fe12085a0100000066c21c21b3eebd3e367dd23b (good)
;; QUESTION SECTION:
;www.wang.org.                  IN      A

;; ANSWER SECTION:
www.wang.org.           86400   IN      A       172.25.254.10

;; Query time: 0 msec
;; SERVER: 172.25.254.100#53(172.25.254.100)
;; WHEN: Mon Aug 19 00:06:57 CST 2024
;; MSG SIZE  rcvd: 85
[root@nginx-node1 tcpconf.d]# dig www.wang.org @172.25.254.100

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

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 1232
; COOKIE: 9dd1c45b5d73b1e60100000066c21c25048edd7237f946a7 (good)
;; QUESTION SECTION:
;www.wang.org.                  IN      A

;; ANSWER SECTION:
www.wang.org.           86400   IN      A       172.25.254.20

;; Query time: 1 msec
;; SERVER: 172.25.254.100#53(172.25.254.100)
;; WHEN: Mon Aug 19 00:07:01 CST 2024
;; MSG SIZE  rcvd: 85

2.mysql

[root@web10 ~]# vim /etc/my.cnf.d/mariadb-server.cnf

[root@web10 ~]# vim /etc/my.cnf.d/mariadb-server.cnf
[root@web10 ~]# systemctl restart mariadb
[root@web10 ~]# mysql
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 3
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)]> create user wang@'%' identified by 'wang';
Query OK, 0 rows affected (0.001 sec)

MariaDB [(none)]> grant all on *.* to wang@'%';
Query OK, 0 rows affected (0.001 sec)

MariaDB [(none)]> quit
Bye

[root@web20 named]# vim /etc/my.cnf.d/mariadb-server.cnf

[root@web20 named]# vim /etc/my.cnf.d/mariadb-server.cnf
[root@web20 named]# systemctl restart mariadb
[root@web20 named]# mysql
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 3
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)]> create user wang@'%' identified by 'wang';
Query OK, 0 rows affected (0.001 sec)

MariaDB [(none)]>  grant all on *.* to wang@'%';
Query OK, 0 rows affected (0.000 sec)

MariaDB [(none)]> quit
Bye

负载均衡

[root@nginx-node1 conf.d]# cd /usr/local/nginx/tcpconf.d
[root@nginx-node1 tcpconf.d]# vim dns.conf
stream {

    upstream dns {
        server 172.25.254.10:53 fail_timeout=15s max_fails=3;
        server 172.25.254.20:53 fail_timeout=15s max_fails=3;
    }

    upstream mysql {
        server 172.25.254.10:3306 fail_timeout=15s max_fails=3;
        server 172.25.254.20:3306 fail_timeout=15s max_fails=3;
    }

    server {
        listen 3306;
        proxy_timeout 60s;
        proxy_pass mysql;
    }

    server {
        listen 53 udp reuseport;
        proxy_timeout 20s;
        proxy_pass dns;
    }
}


[root@nginx-node1 tcpconf.d]# nginx -s reload
[root@nginx-node1 tcpconf.d]# netstat -antlupe | grep 3306
tcp        0      0 0.0.0.0:3306            0.0.0.0:*               LISTEN      0          69433      2744/nginx: master


[root@nginx-node1 tcpconf.d]# dnf install mariadb -y
[root@nginx-node1 tcpconf.d]# mysql -u wang -p -h 172.25.254.100
Enter password:          #密码:wang
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 4
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.001 sec)

MariaDB [(none)]> quit
Bye
[root@nginx-node1 tcpconf.d]# mysql -u wang -p -h 172.25.254.100
Enter password:
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 5
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.001 sec)

6.3实现FastCGI

6.3.1 FastCGI配置指令
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
}

6.3.2 Nginx与php-fpm在同一服务器

编译安装更方便自定义参数或选项,所以推荐大家使用源码编译

官方网站:www.php.net

1.源码编译php

1.首先重新安装编译nginx

#如果原先有nginx,停止并删除
[root@nginx-node1 ~]# cd nginx-1.26.1/
[root@nginx-node1 nginx-1.26.1]# rm -fr /usr/local/nginx/
[root@nginx-node1 nginx-1.26.1]# make clean
rm -rf Makefile objs
[root@nginx-node1 nginx-1.26.1]# ls
auto  CHANGES  CHANGES.ru  conf  configure  contrib  html  LICENSE  man  README  src

#下载新的nginx,安装编译
[root@node-2 nginx-1.26.1]# dnf install gcc pcre-devel zlib-devel openssl-devel -y
[root@node-2 nginx-1.26.1]# ./configure --prefix=/apps/nginx --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module --add-module=/root/memc-nginx-module-0.20 --add-module=/root/srcache-nginx-module-0.33

[root@node-2 nginx-1.26.1]# make && make install
[root@node-2 nginx-1.26.1]# nginx -v
nginx version: nginx/1.26.1
[root@node-2 nginx-1.26.1]# cd /usr/local/nginx/
[root@node-2 nginx]# ls
conf  html  logs  sbin
[root@node-2 nginx]# cd sbin/
[root@node-2 sbin]# ls
nginx
[root@node-2 sbin]# useradd -s /sbin/nologin -M nginx
[root@node-2 sbin]# id nginx
用户id=1001(nginx) 组id=1001(nginx) 组=1001(nginx)
[root@node-2 sbin]# ./nginx

2.安装编译php

需要的软件包

#利用yum解决php依赖
[root@Nginx ~]# dnf install -y bzip2 systemd-devel libxml2-devel sqlite-devel libpng-devel libcurl-devel oniguruma-devel


#解压源码并安装
[root@Nginx ~]# ./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-node1 php-8.3.9]# ./configure --prefix=/usr/local/php --with-config-file-pat h=/usr/local/php/etc --enable-fpm --with-fpm-user=nginx --with-fpm-group=nginx --with-cu rl --with-iconv --with-mhash --with-zlib  --with-openssl --enable-mysqlnd  --with-mysqli  --with-pdo-mysql --disable-debug --enable-sockets --enable-soap --enable-xml --enable-f tp --enable-gd --enable-exif --enable-mbstring --enable-bcmath  --with-fpm-systemd


#可能报错
configure: error: Package requirements (oniguruma) were not met:
Package 'oniguruma', required by 'virtual:world', not found


[root@nginx-node1 ~]#  wget https://mirrors.aliyun.com/rockylinux/9.4/devel/x86_64/kicks tart/Packages/o/oniguruma-devel-6.9.6-1.el9.5.x86_64.rpm


#出现下列表示下载成功

+--------------------------------------------------------------------+
| License:                                                           |
| This software is subject to the PHP License, available in this     |
| distribution in the file LICENSE. By continuing this installation  |
| process, you are bound by the terms of this license agreement.     |
| If you do not agree with the terms of this license, you must abort |
| the installation process at this point.                            |
+--------------------------------------------------------------------+

Thank you for using PHP.


[root@nginx-node1 php-8.3.9]# make && make install
[root@nginx-node1 php-8.3.9]# cd
[root@nginx-node1 ~]#
[root@nginx-node1 ~]# ls
公共                           memcache-8.2.tgz
模板                           memc-nginx-module-0.20
视频                           memc-nginx-module-0.20.tar.gz
图片                           nginx-1.24.0
文档                           nginx-1.24.0.tar.gz
下载                           nginx-1.26.1
音乐                           nginx-1.26.1.tar.gz
桌面                           oniguruma-devel-6.9.6-1.el9.5.x86_64.rpm
anaconda-ks.cfg                openresty-1.25.3.1
echo-nginx-module-0.63         openresty-1.25.3.1.tar.gz
echo-nginx-module-0.63.tar.gz  package.xml
index.html                     php-8.3.9
index.html.1                   php-8.3.9.tar.gz
index.html.2                   srcache-nginx-module-0.33.tar.gz
memcache-8.2

2.php相关配置
[root@nginx-node1 ~]# cd /usr/local/php/etc/
[root@nginx-node1 etc]# ls
php-fpm.conf.default  php-fpm.d
[root@nginx-node1 etc]# cp -p php-fpm.conf.default php-fpm.conf

[root@nginx-node1 etc]# vim php-fpm.conf

去掉注释
pid = run/php-fpm.pid #指定pid文件存放位置

[root@nginx-node1 etc]# ll /usr/local/php/var/run/
总用量 0
[root@nginx-node1 etc]# cd php-fpm.d/
[root@nginx-node1 php-fpm.d]# ls
www.conf.default
[root@nginx-node1 php-fpm.d]# cp www.conf.default www.conf -p

[root@nginx-node1 php-fpm.d]# vim www.conf
[root@nginx-node1 php-fpm.d]# cd ..
[root@nginx-node1 etc]# cd
[root@nginx-node1 ~]# cd php-8.3.9/
[root@nginx-node1 php-8.3.9]# cp php.ini-production /usr/local/php/etc/php.ini
[root@nginx-node1 php-8.3.9]# cd
[root@nginx-node1 ~]# cd /usr/local/php/etc/
[root@nginx-node1 etc]# ls
php-fpm.conf  php-fpm.conf.default  php-fpm.d  php.ini

[root@nginx-node1 etc]# vim php.ini
[Date]
; Defines the default timezone used by the date functions
; https://php.net/date.timezone
date.timezone = Asia/Shanghai #修改时区

[root@nginx-node1 etc]# timedatectl list-timezones | grep Asia/Shanghai
Asia/Shanghai

#生成启动文件
[root@nginx-node1 etc]# cd /root/php-8.3.9/
[root@nginx-node1 php-8.3.9]# cd sapi/f
fpm/    fuzzer/
[root@nginx-node1 php-8.3.9]# cd sapi/fpm/
[root@nginx-node1 fpm]# cp php-fpm.service /lib/systemd/system/
[root@nginx-node1 fpm]# systemctl daemon-reload
[root@nginx-node1 fpm]# vim /lib/sys
sysctl.d/   sysimage/   systemd/    sysusers.d/

[root@nginx-node1 fpm]# 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-node1 fpm]# systemctl daemon-reload
[root@nginx-node1 fpm]# systemctl restart php-fpm.service
[root@nginx-node1 fpm]# netstat -antlupe | grep php
tcp        0      0 127.0.0.1:9000          0.0.0.0:*               LISTEN      0           114573     141107/php-fpm: mas
[root@nginx-node1 fpm]# cd /usr/local/php/
[root@nginx-node1 php]# ls
bin  etc  include  lib  php  sbin  var
[root@nginx-node1 php]# cd /etc/php
php.d/     php-fpm.d/
[root@nginx-node1 php]# cd /etc/php-fpm.d/
[root@nginx-node1 php-fpm.d]# vim www.conf
[root@nginx-node1 php-fpm.d]# cd /usr/local/php/bin

#添加环境变量
[root@nginx-node1 bin]# vim ~/.bash_profile
[root@nginx-node1 bin]# source  ~/.bash_profile

3.php测试页面
[root@nginx-node1 bin]# mkdir -p /data/web/php
[root@nginx-node1 bin]# cd /data/web/php

[root@nginx-node1 php]# vim index.php
<?php
phpinfo();
?>

4.Nginx配置转发
[root@nginx-node1 nginx-1.26.1]# cd /usr/local/nginx
[root@nginx-node1 nginx]# vim conf/nginx.conf
[root@nginx-node1 nginx]# mkdir conf.d
[root@nginx-node1 nginx]# cd /usr/local/nginx/conf.d/
[root@nginx-node1 conf.d]# vim vhosts.conf
server {
    listen 80;
    server_name www.wang.org;
    root /data/web/html;
    index index.html;

    location ~ \.php$ {
        root /data/web/php;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        include fastcgi.conf;
   }
}

[root@nginx-node1 conf.d]# nginx -s reload

不能写*

127.0.0.1:9000或 listen = 0.0.0.0:9000

6.3.3 php动态扩展模块

1.安装memcachemokuai
[root@nginx-node1 ~]#tar zxf memcache-8.2.tgz
[root@nginx-node1 ~]# cd memcache-8.2/
[root@nginx-node1 memcache-8.2]# dnf install autoconf -y
[root@nginx-node1 memcache-8.2]# phpize
Configuring for:
PHP Api Version:         20200930
Zend Module Api No:      20200930
Zend Extension Api No:   420200930
[root@nginx-node1 memcache-8.2]# ls
autom4te.cache  config.m4     CREDITS      LICENSE        src
build           configure     docker       memcache.php   tests
config9.m4      configure.ac  Dockerfile   README
config.h.in     config.w32    example.php  run-tests.php
[root@nginx-node1 memcache-8.2]# ./configure && make && make install
[root@nginx-node1 memcache-8.2]#ls /usr/local/php/lib/php/extensions/no-debug-non-zts20230831/
memcache.so opcache.so

2.复制测试文件到nginx发布目录中
[root@nginx-node1 memcache-8.2]# cp example.php memcache.php  /data/web/php/
[root@nginx-node1 memcache-8.2]# vim /data/web/
download/  errorpage/ html/      php/       test1/     wang/
[root@nginx-node1 memcache-8.2]# vim /data/web/php/memcache.php
define('ADMIN_USERNAME','admin'); // Admin Username
define('ADMIN_PASSWORD','lee'); // Admin Password
define('DATE_FORMAT','Y/m/d H:i:s');
define('GRAPH_SIZE',200);
define('MAX_ITEM_DUMP',50);
$MEMCACHE_SERVERS[] = 'localhost:11211'; // add more as an array
#$MEMCACHE_SERVERS[] = 'mymemcache-server2:11211'; // add more as an array

3.配置php加载memcache模块
[root@nginx-node1 ~]# vim /usr/local/php/etc/php.ini

4.部署memcached
[root@nginx-node1 ~]# yum install memcached -y
[root@nginx-node1 ~]# cat /etc/sysconfig/memcached
PORT="11211"
USER="memcached"
MAXCONN="1024"
CACHESIZE="64"
OPTIONS="-l 127.0.0.1,::1"

[root@nginx-node1 ~]# systemctl restart memcached
[root@nginx-node1 ~]# netstat -antlupe | grep memcache
tcp        0      0 127.0.0.1:11211         0.0.0.0:*               LISTEN      97       7        132283     153128/memcached
tcp6       0      0 ::1:11211               :::*                    LISTEN      97       7        132284     153128/memcached

测试

Web Page Under Construction

6.3.4 php高速缓存

[root@nginx-node1 ~]# vim /usr/local/nginx/conf.d/vhost.conf
upstream memcache {
	server 127.0.0.1:11211;
	keepalive 512;
}
server {
	listen 80;
	server_name www.wang.org;
	root /data/web;
	
	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-node1 ~]# nginx -t
[root@nginx-node1 ~]# nginx -s reload

七、nginx二次版本开发

7.1 openresty

编译安装openresty
[root@nginx-node1 ~]# cd openresty-1.25.3.1/
[root@nginx-node1 openresty-1.25.3.1]# ./configure --prefix=/usr/local/openresty --with-http_realip_module --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-node1 openresty-1.25.3.1]# make && make install
[root@nginx-node1 openresty-1.25.3.1]# cd /usr/local/openresty/
[root@nginx-node1 openresty]# ls
bin  COPYRIGHT  luajit  lualib  nginx  pod  resty.index  site
[root@nginx-node1 openresty]# cd bin/
[root@nginx-node1 bin]# ls
md2pod.pl  nginx-xml2pod  openresty  opm  resty  restydoc  restydoc-index
[root@nginx-node1 bin]# ll
总用量 168
-rwxr-xr-x 1 root root 19185  8月 19 19:20 md2pod.pl
-rwxr-xr-x 1 root root 15994  8月 19 19:20 nginx-xml2pod
lrwxrwxrwx 1 root root    37  8月 19 19:20 openresty -> /usr/local/openresty/nginx/sbin/nginx
-rwxr-xr-x 1 root root 63650  8月 19 19:20 opm
-rwxr-xr-x 1 root root 36881  8月 19 19:20 resty
-rwxr-xr-x 1 root root 14957  8月 19 19:20 restydoc
-rwxr-xr-x 1 root root  8873  8月 19 19:20 restydoc-index
[root@nginx-node1 bin]# pwd
/usr/local/openresty/bin
[root@nginx-node1 bin]# vim ~/.bash_profile
export PATH=$PATH:/usr/local/nginx/sbin:/usr/local/php/bin:/usr/local/php/sbin:/usr/local/openresty/bin

[root@nginx-node1 bin]# openresty

  • 18
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值