高性能web服务器

一.Web 服务基础介绍

正常情况下的单次web服务访问流程:

 

1.Web 服务介绍

1.1Apache 经典的 Web 服务端

Apache起初由美国的伊利诺伊大学香槟分校的国家超级计算机应用中心开发 ,目前经历了两大版本分别是1.X和2.X其可以通过编译安装实现特定的功能。

1.2.1.1 Apache prefork 模型

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

1.2.1.2 Apache worker 模型

一种多进程和多线程混合的模型 有一个控制进程,启动多个子进程 每个子进程里面包含固定的线程 使用线程程来处理请求 当线程不够使用的时候会再启动一个新的子进程,然后在进程里面再启动线程处理请求 由于其使用了线程处理请求,因此可以承受更高的并发。

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

1.2.1.3 Apache event模型

Apache中最新的模式,2012年发布的apache 2.4.X系列正式支持event 模型,属于事件驱动模型(epoll)

每个进程响应多个请求,在现在版本里的已经是稳定可用的模式 它和worker模式很像,最大的区别在于,它解决了keepalive场景下长期被占用的线程的资源浪费问题 (某些线程因为被keepalive,空挂在哪里等待,中间几乎没有请求过来,甚至等到超时)event MPM中,会有一个专门的线程来管理这些keepalive类型的线程 当有真实请求过来的时候,将请求传递给服务线程,执行完毕后,又允许它释放。这样增强了高并发场 景下的请求处理能力。

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

1.2 Nginx-高性能的 Web 服务端

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或者进行二次开发。

1.3用户访问体验和性能

互联网存在用户速度体验的1-3-10原则,即1秒最优,1-3秒较优,3~10秒比较慢,10秒以上用户无法接 受。用户放弃一个产品的代价很低,只是换一个URL而已。

全球最大搜索引擎 Google:慢500ms = 20% 将放弃访问。 全球最大的电商零售网站亚马逊:慢100ms = 1% 将放弃交易 有很多研究都表明,性能对用户的行为有很大的影响:

79%的用户表示不太可能再次打开一个缓慢的网站

47%的用户期望网页能在2秒钟以内加载

40%的用户表示如果加载时间超过三秒钟,就会放弃这个网站 页面加载时间延迟一秒可能导致转换损失7%,页面浏览量减少11% 8秒定律:用户访问一个网站时,如果等待网页打开的时间超过8秒,会有超过30%的用户放弃等待。

影响用户体验的因素

客户端 :
客户端硬件配置 
客户端网络速率 
客户端与服务端距离

服务器: 
服务端网络速率 
服务端硬件配置 
服务端架构设计 
服务端应用程序工作模式 
服务端并发数量服务端响应文件大小及数量 buffer cache
服务端I/O压力1.2.4 服务端 I/O 流程

1.4服务端 I/O 流程

I/O在计算机中指Input/Output, IOPS (Input/Output Per Second)即每秒的输入输出量(或读写次数), 是衡量磁盘性能的主要指标之一。IOPS是指单位时间内系统能处理的I/O请求数量,一般以每秒处理的

I/O请求数量为单位,I/O请求通常为读或写数据操作请求。 一次完整的I/O是用户空间的进程数据与内核空间的内核数据的报文的完整交换,但是由于内核空间与用 户空间是严格隔离的,所以其数据交换过程中不能由用户空间的进程直接调用内核空间的内存数据,而 是需要经历一次从内核空间中的内存数据copy到用户空间的进程内存当中,所以简单说I/O就是把数据从 内核空间中的内存数据复制到用户空间中进程的内存当中。

二.Nginx 编译安装

编译器介绍:

源码安装需要提前准备标准的编译器,GCC的全称是(GNU Compiler collection),其有GNU开发,并以

GPL即LGPL许可,是自由的类UNIX即苹果电脑Mac OS X操作系统的标准编译器,因为GCC原本只能处理C语 言,所以原名为GNU C语言编译器,后来得到快速发展,可以处理C++,Fortran,pascal,objective C,

java以及Ada等其他语言,此外还需要Automake工具,以完成自动创建Makefile的工作,Nginx的一些模块 需要依赖第三方库,比如: pcre(支持rewrite),zlib(支持gzip模块)和openssl(支持ssl模块) 等

[root@nginx nginx-1.24.0]# ls /usr/local/nginx/
conf  html  logs  sbin

1.编译安装 Nginx

[root@nginx ~]# ls
公共  模板  视频  图片  文档  下载  音乐  桌面  anaconda-ks.cfg  mnt  nginx-1.24.0.tar.gz
[root@nginx ~]# dnf install gcc pcre-devel zlib-devel openssl-devel -y
[root@nginx ~]# tar zxf nginx-1.24.0.tar.gz
[root@nginx ~]# useradd -s /sbin/nologin -M nginx
useradd:用户“nginx”已存在
[root@nginx ~]# cd nginx-1.24.0/
[root@nginx nginx-1.24.0]# ls
auto  CHANGES  CHANGES.ru  conf  configure  contrib  html  LICENSE  man  README  src

[root@Nginx nginx-1.24.0]# ./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.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_stub_status_module \--with-http_gzip_static_module \--with-pcre \--with-stream \--with-stream_ssl_module \--with-stream_realip_module

[root@nginx nginx-1.24.0]# make && make install
[root@nginx nginx-1.24.0]# 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文件是默认的错误页面提示页面。

logs:用来保存nginx服务器的访问日志错误日志等日志,logs目录可以放在其他路径,比
如/var/logs/nginx里面。

sbin:保存nginx二进制启动脚本,可以接受不同的参数以实现不同的功能。

[root@nginx nginx-1.24.0]# vim ~/.bash_profile
[root@nginx nginx-1.24.0]# source ~/.bash_profile
[root@nginx nginx-1.24.0]# cat ~/.bash_profile
# .bash_profile

# Get the aliases and functions
if [ -f ~/.bashrc ]; then
        . ~/.bashrc
fi

# User specific environment and startup programs
export PATH=$PATH:/usr/local/nginx/sbin

[root@nginx nginx-1.24.0]# nginx -V
nginx version: nginx/1.24.0
built by gcc 11.4.1 20230605 (Red Hat 11.4.1-2) (GCC)
built with OpenSSL 3.0.7 1 Nov 2022
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 nginx-1.24.0]# nginx
[root@apache nginx-1.24.0]# ps ax | grep nginx
  40313 ?        Ss     0:00 nginx: master process nginx
  40314 ?        S      0:00 nginx: worker process
  41937 pts/0    S+     0:00 grep --color=auto nginx


[root@nginx nginx-1.24.0]# vim auto/cc/gcc

2.验证版本和编译的参数

[root@nginx nginx-1.24.0]# vim ~/.bash_profile
[root@nginx nginx-1.24.0]# source ~/.bash_profile
[root@nginx nginx-1.24.0]# cat ~/.bash_profile

# .bash_profile

# Get the aliases and functions

if [ -f ~/.bashrc ]; then
        . ~/.bashrc
fi

# User specific environment and startup programs

export PATH=$PATH:/usr/local/nginx/sbin

[root@nginx nginx-1.24.0]# nginx -V
nginx version: nginx/1.24.0
built by gcc 11.4.1 20230605 (Red Hat 11.4.1-2) (GCC)
built with OpenSSL 3.0.7 1 Nov 2022
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 nginx-1.24.0]# nginx
[root@apache nginx-1.24.0]# ps ax | grep nginx
  40313 ?        Ss     0:00 nginx: master process nginx
  40314 ?        S      0:00 nginx: worker process
  41937 pts/0    S+     0:00 grep --color=auto nginx

[root@nginx nginx-1.24.0]# vim auto/cc/gcc

三.nginx平滑升级和回滚处理

有时候我们需要对Nginx版本进行升级以满足对其功能的需求,例如添加新模块,需要新功能,而此时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 ~]# tar zxf nginx-1.26.1.tar.gz
[root@nginx ~]# cd nginx-1.26.1/
[root@nginx nginx-1.26.1]# ls
auto  CHANGES  CHANGES.ru  conf  configure  contrib  html  LICENSE  man  README  src
[root@nginx 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_stub_status_module \--with-http_gzip_static_module \--with-pcre \--with-stream \--with-stream_ssl_module \--with-stream_realip_module

#注意只要make无需要make install
[root@nginx nginx-1.26.1]# make
[root@nginx nginx-1.26.1]# ll objs/nginx /usr/local/nginx/sbin/nginx
-rwxr-xr-x. 1 root root 5756968  8月 15 12:07 objs/nginx
-rwxr-xr-x. 1 root root 5678264  8月 15 11:57 /usr/local/nginx/sbin/nginx
[root@nginx nginx-1.26.1]# cd /usr/local/nginx/sbin/
[root@nginx sbin]# ls
nginx
[root@nginx sbin]# cp nginx nginx.bak
[root@nginx sbin]# ls
nginx  nginx.bak
[root@nginx ~]# ls
公共  图片  音乐             echo-nginx-module-0.63.tar.gz  nginx-1.24.0.tar.gz  srcache-nginx-module-0.33.tar.gz
模板  文档  桌面             mnt                            nginx-1.26.1
视频  下载  anaconda-ks.cfg  nginx-1.24.0                   nginx-1.26.1.tar.gz
[root@nginx ~]# cd /root/nginx-1.26.1/
[root@nginx nginx-1.26.1]# ls
auto  CHANGES  CHANGES.ru  conf  configure  contrib  html  LICENSE  Makefile  man  objs  README  src
[root@nginx nginx-1.26.1]# \cp -f /root/nginx-1.26.1/objs/nginx /usr/local/nginx/sbin
[root@nginx nginx-1.26.1]# ps aux | grep nginx

四.nginx核心配置

1.配置文件说明

nginx 官方帮助文档:nginx documentation

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

主配置文件:nginx.conf

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

fastcgi, uwsgi,scgi 等协议相关的配置文件

mime.types:支持的mime类型,MIME(Multipurpose Internet Mail Extensions)多用途互联网邮 

件扩展类型,MIME消息能包含文本、图像、音频、视频以及其他应用程序专用的数据,是设定某 

种扩展名的文件用一种应用程序来打开的方式类型,当该扩展名文件被访问的时候,浏览器会自动 

使用指定应用程序来打开。多用于指定一些客户端自定义的文件名,以及一些媒体文件打开方式。

nginx 配置文件格式说明:

配置文件由指令与指令块构成 
每条指令以;分号结尾,指令与值之间以空格符号分隔 
可以将多条指令放在同一行,用分号分隔即可,但可读性差,不推荐 指令块以{ }大括号将多条指令组织在一起,且可以嵌套指令块

include语句允许组合多个配置文件以提升可维护性 
使用#符号添加注释,提高可读性 
使用$符号使用变量 
部分指令的参数支持正则表达式

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

Main 全局配置段常见的配置指令分类:

正常运行必备的配置

优化性能相关的配置

用于调试及定位问题相关的配置

事件驱动相关的配置

默认的nginx.conf 配置文件格式说明

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

user nginx nginx; worker_processes  1;   #启动工作进程数数量

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

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

#(worker_connections * worker_processes)/2 } http { #http块是Nginx服务器配置中的重要部分,缓存、代理和日志格 式定义等绝大多数功能和第三方模块都 #可以在这设置,http块可 以包含多个server块,而一个server块中又可以包含多个location块,

          #server块可以配置文件引入、MIME-Type定义、日志自定义、是 否启用sendfile、连接超时时间和 #单个链接的请求上限等。

  include       mime.types;   default_type application/octet-stream;   sendfile       on; #作为web服务器的时候打开sendfile加快静态文件传输,指定是 否使用

#sendfile系统调用来传输文件

#sendfile系统调用在两个文件描述符之间直接传递数据(完全在 内核中操作) #从而避免了数据在内核缓冲区和用户缓冲区之间的拷贝,操作效率 很高,被称之为零拷贝,

#硬盘 >> kernel buffer (快速拷贝到kernelsocket buffer) >>协议栈。

  keepalive_timeout  65;   #长连接超时时间,单位是秒

  server { #设置一个虚拟机主机,可以包含自己的全局快,同时也可以包含多 个location模块

  #比如本虚拟机监听的端口、本虚拟机的名称和IP配置,多个

server 可以使用一个端口比如都使用 #80端口提供web服务

        listen       80;   #配置server监听的端口

      server_name localhost;   #本server的名称,当访问此名称的时候nginx会调用当前serevr

内部的配置进程匹配。

            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@apache ~]# vim /usr/local/nginx/conf/nginx.conf
[root@apache ~]# nginx -s reload
[root@apache ~]# ps aux | grep nginx
root       50327  0.0  0.0   9864  3428 ?        Ss   20:43   0:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx      53814  0.0  0.1  13760  4744 ?        S    20:52   0:00 nginx: worker process
nginx      53815  0.0  0.1  13760  4744 ?        S    20:52   0:00 nginx: worker process
root       53829  0.0  0.0 221680  2360 pts/0    S+   20:52   0:00 grep --color=auto nginx

[root@Nginx ~]# vim /etc/security/limits.conf 
*        -    nofile     100000 
[root@Nginx ~]# sudo -u nginx ulimit -n 100000

[root@apache ~]# dnf install httpd_tools -y
[root@apache ~]# ab -n 100 -c 50 http://172.25.254.100/index.html
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 172.25.254.100 (be patient).....done


Server Software:        nginx/1.24.0
Server Hostname:        172.25.254.100
Server Port:            80

Document Path:          /index.html
Document Length:        615 bytes

Concurrency Level:      50
Time taken for tests:   0.010 seconds
Complete requests:      100
Failed requests:        0
Total transferred:      84800 bytes
HTML transferred:       61500 bytes
Requests per second:    9595.09 [#/sec] (mean)
Time per request:       5.211 [ms] (mean)
Time per request:       0.104 [ms] (mean, across all concurrent requests)
Transfer rate:          7945.93 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        1    2   0.3      2       3
Processing:     0    1   0.6      2       2
Waiting:        0    1   0.4      1       2
Total:          1    3   0.8      3       5
WARNING: The median and mean for the processing time are not within a normal deviation
        These results are probably not that reliable.

Percentage of the requests served within a certain time (ms)
  50%      3
  66%      4
  75%      4
  80%      4
  90%      4
  95%      4
  98%      4
  99%      5
 100%      5 (longest request)
[root@apache ~]# cat /usr/local/nginx/logs/error.log
[root@apache ~]# cat /usr/local/nginx/logs/access.log

[root@apache nginx-1.24.0]# nginx -v      查看版本
nginx version: nginx/1.24.0

[root@apache nginx-1.24.0]# 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 ~]# vim /usr/local/nginx/conf/nginx.conf    nginx配置文件
[root@apache ~]# nginx -g "worker_processes 6;"    进配置文件把名字注释了才能添加
[root@apache ~]# ps aux | grep nginx
root       47735  0.0  0.0   9864   928 ?        Ss   20:36   0:00 nginx: master process nginx -g worker_processes 6;
nginx      47736  0.0  0.1  13760  4736 ?        S    20:36   0:00 nginx: worker process
nginx      47737  0.0  0.1  13760  4632 ?        S    20:36   0:00 nginx: worker process
nginx      47738  0.0  0.1  13760  4612 ?        S    20:36   0:00 nginx: worker process
nginx      47739  0.0  0.1  13760  4736 ?        S    20:36   0:00 nginx: worker process
nginx      47740  0.0  0.1  13760  4736 ?        S    20:36   0:00 nginx: worker process
nginx      47741  0.0  0.1  13760  4736 ?        S    20:36   0:00 nginx: worker process
root       48092  0.0  0.0 221680  2364 pts/0    S+   20:37   0:00 grep --color=auto nginx

3.新建一个pc站点

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

设置行距:
[root@apache ~]# vim ~/.vimrc
[root@apache ~]# cat ~/.vimrc
set ts=4 ai sw =4


[root@apache ~]# mkdir -p /usr/local/nginx/conf.d
[root@apache ~]# vim  /usr/local/nginx/conf.d/vhost.conf
[root@apache ~]# cat  /usr/local/nginx/conf.d/vhost.conf
server {
   listen 80;
   server_name www.timinglee.org;
   root /data/web/html;
   index index.html;
}

[root@apache ~]# mkdir -p /data/web/html
[root@apache ~]# echo www.timinglee.org > /data/web/html/index.html
[root@apache ~]# 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

4.root和alias

[root@apache ~]# vim  /usr/local/nginx/conf.d/vhost.conf
[root@apache ~]# mkdir -p /data/web/test1
[root@apache ~]# echo /data/web/test1  > /data/web/test1/index.html
[root@apache ~]# cat  /usr/local/nginx/conf.d/vhost.conf
server {
   listen 80;
   server_name www.timinglee.org;
   root /data/web/html;
   index index.html;
   location /test1/ {
          root /data/web;
                  }
}
[root@apache ~]# 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@apache ~]# nginx -s reload
[root@apache ~]# tail  /usr/local/nginx/logs/error.log  若有错误看日志
​

[root@apache ~]# vim  /usr/local/nginx/conf.d/vhost.conf
[root@apache ~]# cat  /usr/local/nginx/conf.d/vhost.conf
server {
   listen 80;
   server_name www.timinglee.org;
   root /date/web/html;
   index index.html;
   location /test1/ {
          root /data/web;
                  }
   location /tets2 {
          alias /data/web/test1;
   }
}

5.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前,表示包含正则表达式并且转义字符。可以将 . * ?等转义为普通符号


优先级大小:
#对目录匹配   ~*  ~  > 不带符号 >  ^~  >  =     #=不能指定目录所以排在最后
#对文件匹配   = > (~*  ~) > 不带符号  >  ^~

5.1优先级大小:

# 对目录匹配   ~*  ~  > 不带符号 >  ^~  >    =  不能指定目录,只能指定文件
#对文件匹配   = > (~*  ~) > 不带符号  >  ^~

[root@apache ~]# mkdir -p /data/web{1..2}/test
[root@apache ~]# echo test page1  > /data/web1/test/index.html
[root@apache ~]# echo test page2  > /data/web2/test/index.html
[root@apache ~]# vim /usr/local/nginx/conf.d/vhost.conf
[root@apache ~]# cat /usr/local/nginx/conf.d/vhost.conf
server {
   listen 80;
   server_name www.timinglee.org;
   root /data/web/html;
   index index.html;

  location /test {
          root /data/web2;    web2和web1谁写在前面就运行谁的结果
                  }

  location = /test {
         root /data/web1;
                 }
}
[root@apache ~]# nginx -s reload

[root@apache ~]# mkdir -p /data/web3/test/index.html
[root@apache ~]# mkdir -p /data/web4/test/index.html
[root@apache ~]# mkdir -p /data/web5/test/index.html
[root@apache ~]# echo web1  > /data/web1/test/index.html
[root@apache ~]# echo web2  > /data/web2/test/index.html
[root@apache ~]# echo web3  > /data/web3/test/index.html
[root@apache ~]# vim /usr/local/nginx/conf.d/vhost.conf
[root@apache ~]# cat /usr/local/nginx/conf.d/vhost.conf
server {
   listen 80;
   server_name www.timinglee.org;
   root /data/web/html;
   index index.html;

  location /test {
          root /data/web2;
          }

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

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

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

   location ~ /html$ {
     root /data/web4;
     }
}
~

[root@apache ~]# nginx -s reloa

五.nginx的启动脚本

[root@apache ~]# vim /lib/systemd/system/nginx.service
[root@apache ~]# 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@apache ~]# systemctl daemon-reload
[root@apache ~]# nginx -s stop
[root@apache ~]# ps aux | grep nginx
root       50216  0.0  0.0 221680  2344 pts/0    S+   20:42   0:00 grep --color=auto nginx
[root@apache ~]# systemctl enable --now nginx
Created symlink /etc/systemd/system/multi-user.target.wants/nginx.service → /usr/lib/systemd/system/nginx.service.
[root@apache ~]# ps aux | grep nginx
root       50327  0.0  0.0   9864   928 ?        Ss   20:43   0:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx      50328  0.0  0.1  13760  4728 ?        S    20:43   0:00 nginx: worker process
root       50348  0.0  0.0 221680  2360 pts/0    S+   20:43   0:00 grep --color=auto nginx

六.nginx 账户认证功能 创建默认认证文件

[root@apache ~]# htpasswd -cm /usr/local/nginx/.htpasswd admin
New password:(123456)
Re-type new password:
Adding password for user admin
[root@apache ~]# cat /usr/local/nginx/.htpasswd
admin:$apr1$rbbK8mqA$WAQYxSS1iTY4X7hKNuNgT1

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

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

[root@apache ~]# mkdir /data/web/lee
[root@apache ~]# echo lee > /data/web/lee/index.html
[root@apache ~]# nginx -s reload

七.自定义错误页面

[root@apache ~]# vim /usr/local/nginx/conf.d/vhost.conf
[root@apache ~]# cat /usr/local/nginx/conf.d/vhost.conf
server {
   listen 80;
   server_name www.timinglee.org;
   error_page 404 /40x.html;
   root /data/web/html;
   index index.html;
   
  location =/40x.html {
       root /data/web/errorpage;    #指定错误页面
  }
}
[root@apache ~]# mkdir -p /data/web/errorpage
[root@apache ~]# echo error page > /data/web/errorpage/40x.html
[root@apache ~]# nginx -s reload

八.自定义错误日志 日志重定向

[root@apache ~]# vim /usr/local/nginx/conf.d/vhost.conf
[root@apache ~]# cat /usr/local/nginx/conf.d/vhost.conf
server {
   listen 80;
   server_name www.timinglee.org;
   error_page 404 /40x.html;
   root /data/web/html;
   index index.html;
   error_log  /var/log/timinglee.org/error.log;
   access_log  /var/log/timinglee.org/access.log;

  location /lee{
       root /data/web;
           auth_basic "login password !!";
           auth_basic_user_file "/usr/local/nginx/.htpasswd";
           }
  location =/40x.html {
       root /data/web/errorpage;
  }

}
[root@apache ~]# mkdir -p  /var/log/timinglee.org
[root@apache ~]# nginx -s reload
[root@apache ~]# curl www.timinglee.org
www.timinglee.org
[root@apache ~]# curl www.timinglee.org/aaa
error default
[root@apache ~]# cat /var/log/timinglee.org/access.log
172.25.254.1 - - [16/Aug/2024:14:30:11 +0800] "GET / HTTP/1.1" 200 18 "-" "curl/8.4.0"
172.25.254.1 - - [16/Aug/2024:14:30:23 +0800] "GET / HTTP/1.1" 200 18 "-" "curl/8.4.0"

[root@apache ~]# cat /var/log/timinglee.org/error.log

[root@apache ~]# curl www.timinglee.org
curl: (6) Could not resolve host: www.timinglee.org

若报这个错误,去配置本地解析
[root@apache ~]# vim /etc/hosts

九.检测文件是否存在

[root@apache ~]# vim /usr/local/nginx/conf.d/vhost.conf
[root@apache ~]# mkdir /data/web/html/error
[root@apache ~]# echo error default > /data/web/html/error/default.html
[root@apache ~]# nginx -s reload

[root@apache ~]# cat /data/web/html/error/default.html
error default
[root@apache ~]# cat /data/web/html/error/index.html
error default

十.长连接的配置

[root@apache ~]# dnf install telnet -y     测试工具

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

[root@apache ~]# telnet www.timinglee.org 80
Trying 172.25.254.100...
Connected to www.timinglee.org.
Escape character is '^]'.
GET / HTTP/1.1
HOST: www.timinglee.org
Connection closed by foreign host.

十一.作为下载服务器的配置

[root@apache ~]# mkdir /data/web/download
[root@apache ~]# vim /usr/local/nginx/conf.d/vhost.conf
[root@apache ~]# dd if=/dev/zero of=/data/web/download/wanglife bs=1M count=100
记录了100+0 的读入
记录了100+0 的写出
104857600字节(105 MB,100 MiB)已复制,0.07638 s,1.4 GB/s
[root@apache ~]# nginx -s reload

Nginx的高级配置

注意本地解析和虚拟机内的解析

Nginx的状态页

基于nginx 模块 ngx_http_stub_status_module 实现
在编译安装nginx的时候需要添加编译参数 --with-http_stub_status_module
否则配置完成之后监测会是提示法错误

注意: 状态页显示的是整个服务器的状态,而非虚拟主机的状态
#配置示例:

location /nginx_status {
  stub_status;
   auth_basic           "auth login";
   auth_basic_user_file /apps/nginx/conf/.htpasswd;
   allow 192.168.0.0/16;
   allow 127.0.0.1;
   deny all;
 }
#状态页用于输出nginx的基本状态信息:

#输出信息示例:

Active connections: 291
server accepts handled requests
 16630948 16630948 31070465
 上面三个数字分别对应accepts,handled,requests三个值

Reading: 6 Writing: 179 Waiting: 106
Active connections: #当前处于活动状态的客户端连接数

 #包括连接等待空闲连接数=reading+writing+waiting
 
accepts: #统计总值,Nginx自启动后已经接受的客户端请求连接的总数。
handled: #统计总值,Nginx自启动后已经处理完成的客户端请求连接总数
 #通常等于accepts,除非有因worker_connections限制等被拒绝的
连接
 
requests: #统计总值,Nginx自启动后客户端发来的总的请求数
Reading: #当前状态,正在读取客户端请求报文首部的连接的连接数
#数值越大,说明排队现象严重,性能不足

Writing: #当前状态,正在向客户端发送响应报文过程中的连接数,数值越大,说明
访问量很大
Waiting: #当前状态,正在等待客户端发出请求的空闲连接数

开启 keep-alive的情况下,这个值等于active – (reading+writing)

[root@apache ~]# vim /etc/hosts
[root@apache ~]# vim /usr/local/nginx/conf.d/status.conf
[root@apache ~]# nginx -s reload

 

Nginx 压缩功能

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

Nginx对文件的压缩功能是依赖于模块 ngx_http_gzip_module,默认是内置模块

配置指令如下:
#启用或禁用gzip压缩,默认关闭

gzip on | off; 
#压缩比由低到高从1到9,默认为1,值越高压缩后文件越小,但是消耗cpu比较高。基本设定未4或者5
gzip_comp_level 4;
#禁用IE6 gzip功能,早期的IE6之前的版本不支持压缩

gzip_disable "MSIE [1-6]\."; 
#gzip压缩的最小文件,小于设置值的文件将不会压缩

gzip_min_length 1k; 
#启用压缩功能时,协议的最小版本,默认HTTP/1.1
gzip_http_version 1.0 | 1.1; 
#指定Nginx服务需要向服务器申请的缓存空间的个数和大小,平台不同,默认:32 4k或者16 8k;
gzip_buffers number size;  
#指明仅对哪些类型的资源执行压缩操作;默认为gzip_types text/html,不用显示指定,否则出错

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

gzip_vary on | off; 
#预压缩,即直接从磁盘找到对应文件的gz后缀的式的压缩文件返回给用户,无需消耗服务器CPU
#注意: 来自于ngx_http_gzip_static_module模块

gzip_static on | off;

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

[root@apache ~]# mkdir /data/web/html/small.html
[root@apache ~]# rm -fr /data/web/html/small.html
[root@apache ~]# echo hello timinglee > /data/web/html/small.html
[root@apache ~]# 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@apache ~]# nginx -s reload
[root@apache ~]# du -sh /usr/local/nginx/logs/access.log
36K     /usr/local/nginx/logs/access.log
[root@apache ~]# cat /usr/local/nginx/logs/access.log > /data/web/html/big.html
[root@apache ~]# curl --head --compressed 172.25.254.100/small.html
HTTP/1.1 200 OK
Server: nginx/1.24.0
Date: Fri, 16 Aug 2024 08:21:04 GMT
Content-Type: text/html
Content-Length: 16
Last-Modified: Fri, 16 Aug 2024 08:19:57 GMT
Connection: keep-alive
Keep-Alive: timeout=60
ETag: "66bf0bad-10"
Accept-Ranges: bytes

[root@apache ~]# curl --head --compressed 172.25.254.100/big.html
HTTP/1.1 200 OK
Server: nginx/1.24.0
Date: Fri, 16 Aug 2024 08:21:31 GMT
Content-Type: text/html
Last-Modified: Fri, 16 Aug 2024 08:20:46 GMT
Connection: keep-alive
Keep-Alive: timeout=60
Vary: Accept-Encoding
ETag: W/"66bf0bde-839f"
Content-Encoding: gzip


只是在传输过程中会压缩变小,传输是速率会变快,对文件大小本身没有影响
[root@apache ~]# du -sh /data/web/html/big.html
36K     /data/web/html/big.html
[root@apache ~]# du -sh /data/web/html/small.html
4.0K    /data/web/html/small.html

Nginx的版本隐藏

用户在访问nginx的时候,我们可以从报文中获得nginx的版本,相对于裸漏版本号的nginx,我们把其隐 藏起来更安全

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

Nginx 变量使用

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

内置变量的官方文档:Alphabetical index of variables

常用内置变量:

$remote_addr;  #存放了客户端的地址,注意是客户端的公网IP(远程主机的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为任意请求报文首部字段,表示记录请求报文的首部字段,ame的对应的首部字段名需要为小写,如果有横线需要替换为下划线

#示例:  
echo $http_user_agent; 
echo $http_host; 

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

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

echo $arg_id;

#nginx的内置变量

server {
    listen 80;
    server_name var.timinglee.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;
    }
}

 curl -b "key1=lee,key2=lee1" -u lee:lee var.timinglee.org/var?name=lee&&id=6666
 
[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
nginx的自定义变量

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

语法格式:

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

示例:

[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_http_rewrite_module 模块指令

官方文档: Module ngx_http_rewrite_module

if 指令

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

[root@nginx-node1 conf.d]# vim vars.conf
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


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

  }
curl var.timinglee.org/test2/index.html 

set指令

#nginx自定义变量
server {
    listen 80;
    server_name var.timinglee.org;
    root /data/web/html;
    index index.html;

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

}


 curl -b "key1=lee,key2=lee1" -u lee:lee var.timinglee.org/var?name=lee&&id=6666

break指令

[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 {
        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


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

curl  var.timinglee.org/break
curl -A "firefox"  var.timinglee.org/break

return指令

[root@nginx-node1 conf.d]# vim vars.conf
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

#return

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

rewrite 指令

通过正则表达式的匹配来改变URI,可以同时存在一个或多个指令,按照顺序依次对URI进行匹配,
rewrite主要是针对用户请求的URL或者是URI做具体处理 
官方文档:https://nginx.org/en/docs/http/ngx_http_rewrite_module.html#rewrite

语法格式 :rewrite regex replacement [flag];


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

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

301 

正则表达式格式

. #匹配除换行符以外的任意字符

\w #匹配字母或数字或下划线或汉字

\s #匹配任意的空白符

\d #匹配数字

\b #匹配单词的开始或结束

^ #匹配字付串的开始

$ #匹配字符串的结束

\* #匹配重复零次或更多次

\+ #匹配重复一次或更多次

? #匹配重复零次或一次

(n) #匹配重复n次

{n,} #匹配重复n次或更多次

{n,m} #匹配重复n到m次

*? #匹配重复任意次,但尽可能少重复

+? #匹配重复1次或更多次,但尽可能少重复

?? #匹配重复0次或1次,但尽可能少重复

{n,m}? #匹配重复n到m次,但尽可能少重复

{n,}? #匹配重复n次以上,但尽可能少重复

\W  #匹配任意不是字母,数字,下划线,汉字的字符

\S #匹配任意不是空白符的字符

\D #匹配任意非数字的字符

\B #匹配不是单词开头或结束的位置

[^x] #匹配除了x以外的任意字符

[^lee] #匹配除了magedu 这几个字母以外的任意字符

rewrite flag 使用介绍

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

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

rewrite 格式

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

flag 说明

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

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

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

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

rewrite案例: 域名永久与临时重定向

域名的临时的调整,后期可能会变,之前的域名或者URL可能还用、或者跳转的目的域名和URL还会跳 转,这种情况浏览器不会缓存跳转,临时重定向不会缓存域名解析记录(A记录),但是永久重定向会缓存。 示例: 因业务需要,将访问源域名 www.timinglee.org 的请求永久重定向到 www.timinglee.com

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

永久重定向301

域名永久型调整,即域名永远跳转至另外一个新的域名,之前的域名再也不使用,跳转记录可以缓存到 客户端浏览器 永久重定向会缓存DNS解析记录, 浏览器中有 from disk cache 信息,即使nginx服务器无法访问,浏览器也 会利用缓存进行重定向

比如: 京东早期的域名 www.360buy.com 由于与360公司类似,于是后期永久重定向到了 www.jd.com

示例:

rewrite案例: 自动跳转 https
[root@apache nginx]# cd /usr/local/nginx/
[root@apache nginx]# mkdir certs
[root@apache nginx]# openssl req  -newkey  rsa:2048 -nodes -sha256 -keyout /usr/local/nginx/certs/timinglee.org.key  -x509  -days 365 -out /usr/local/nginx/certs/timinglee.org.crt

Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:Shanxi
Locality Name (eg, city) [Default City]:xian
Organization Name (eg, company) [Default Company Ltd]:timinglee
Organizational Unit Name (eg, section) []:webserver
Common Name (eg, your name or your server's hostname) []:www.timinglee.org
Email Address []:admin@timinglee.org

[root@apache nginx]# cd /usr/local/nginx/certs/
[root@apache certs]# ls
timinglee.org.crt  timinglee.org.key
[root@apache certs]# vim /usr/local/nginx/conf.d/vhosts.conf
[root@apache certs]# cat /usr/local/nginx/conf.d/vhosts.conf
server {
    listen 80;
    listen 443 ssl;
    server_name www.timinglee.org;
    root /data/web/html;
    index index.html;
    ssl_certificate /usr/local/nginx/certs/timinglee.org.crt;
    ssl_certificate_key /usr/local/nginx/certs/timinglee.org.key;
    ssl_session_cache    shared:SSL:1m;
    ssl_session_timeout  5m;
}

[root@apache certs]# nginx -s reload

[root@apache certs]# vim /usr/local/nginx/conf.d/vhosts.conf
[root@apache certs]# nginx -s reload
[root@apache certs]# cat /usr/local/nginx/conf.d/vhosts.conf
server {
    listen 80;
    listen 443 ssl;
    server_name www.timinglee.org;
    root /data/web/html;
    index index.html;
    ssl_certificate /usr/local/nginx/certs/timinglee.org.crt;
    ssl_certificate_key /usr/local/nginx/certs/timinglee.org.key;
    ssl_session_cache    shared:SSL:1m;
    ssl_session_timeout  5m;

    location / {
       if ( $scheme = http ){
           rewrite / https://$host redirect;
       }
    }
}
效果图:自动跳转到https
[root@apache certs]# vim /usr/local/nginx/conf.d/vhosts.conf
[root@apache certs]# nginx -s reload
[root@apache certs]# cat /usr/local/nginx/conf.d/vhosts.conf
server {
    listen 80;
    listen 443 ssl;
    server_name www.timinglee.org;
    root /data/web/html;
    index index.html;
    ssl_certificate /usr/local/nginx/certs/timinglee.org.crt;
    ssl_certificate_key /usr/local/nginx/certs/timinglee.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;
        }
    }
}
不存在的路径就会报404的错误,存在的路径就返回自己的值

Nginx的防盗链

[root@apache ~]# vim /usr/local/nginx/conf.d/vhosts.conf
[root@apache ~]# mkdir -p /data/web/html/images
[root@apache ~]# cd  /data/web/html/images
[root@apache images]# ls
微信图片_20230912183800.jpg  nnn.jpg
[root@apache images]# mkdir -p /data/web/html/

两张图片:一张在/data/web/html/images下面
        一张在/data/web/html下面    两张图片最好不要放在一起
        
[root@apache images]# vim /usr/local/nginx/conf.d/vhosts.conf
[root@apache images]# nginx -s reload
[root@apache images]# cat /usr/local/nginx/conf.d/vhosts.conf
server {
    listen 80;
    listen 443 ssl;
    server_name www.timinglee.org;
    root /data/web/html;
    index index.html;
    ssl_certificate /usr/local/nginx/certs/timinglee.org.crt;
    ssl_certificate_key /usr/local/nginx/certs/timinglee.org.key;
    ssl_session_cache    shared:SSL:1m;
    ssl_session_timeout  5m;

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

[root@apache ~]# dnf install httpd
[root@apache ~]# cd /var/www/html
[root@apache html]# ls
index.html
[root@apache html]# vim index.html
[root@apache html]# cat index.html
<html>

  <head>
    <meta http-equiv=Content-Type content="text/html;charset=utf-8">
    <title>盗链</title>
</head>

  <body>
    <img src="http://www.timinglee.org/images/nnn.jpg" >
    <h1 style="color:red">欢迎大家</h1>
    <p><a href=http://www.timinglee.org>ddd</a>hhh</p>
  </body>

</html>
[root@apache html]# systemctl start httpd

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协议转发至指定服务器处理

准备三台主机:172.25.254.100/10/20

在172.25.254.100上测试:

[root@apache ~]# curl 172.25.254.10
172.25.254.10
[root@apache ~]# curl 172.25.254.20
172.25.254.20

[root@apache ~]# vim /usr/local/nginx/conf.d/vhosts.conf
[root@apache ~]# cat /usr/local/nginx/conf.d/vhosts.conf
server {
    listen 80;
        server_name www.timinglee.org;

        location / {
            proxy_pass http://172.25.254.10:80;
        }
    location /static {
            proxy_pass http://172.25.254.20:80;
                }
}
[root@apache ~]# nginx -s reload
[root@apache html]# systemctl enable --now httpd
Created symlink /etc/systemd/system/multi-user.target.wants/httpd.service → /usr/lib/systemd/system/httpd.service.
[root@apache html]# echo 172.25.254.10 > /var/www/html/index.html

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

Nginx的动静分离

[root@apache ~]#vim /usr/local/nginx/conf.d/vhosts.conf
[root@apache ~]# cat /usr/local/nginx/conf.d/vhosts.conf
server {
    listen 80;
        server_name www.timinglee.org;

        location ~ \.php$ {
            proxy_pass http://172.25.254.10:80;
        }
    location /static {
            proxy_pass http://172.25.254.20:8080;
                }
}
[root@apache ~]# nginx -s reload
[root@apache html]# dnf install php -y
[root@apache html]# systemctl restart httpd
[root@apache html]# vim /var/www/html/index.php
[root@apache html]# cat /var/www/html/index.php
<? php
   phpinfo();
?>

Nginx的反向代理的缓存功能

[root@apache ~]# vim /usr/local/nginx/conf/nginx.conf
@@@@内容省略@@@@
 #gzip on;
 proxy_cache_path /apps/nginx/proxy_cache levels=1:2:2 keys_zone=proxycache:20m 
inactive=120s max_size=1g; #配置在nginx.conf http配置段


[root@apache ~]# vim /usr/local/nginx/conf.d/vhosts.conf
[root@apache ~]# cat /usr/local/nginx/conf.d/vhosts.conf
server {
    listen 80;
        server_name www.timinglee.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;
                }
}

[root@apache ~]# nginx -s reload
[root@apache conf]# ab -n1000 -c100 http://www.timinglee.org/static/index.html
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 www.timinglee.org (be patient)
Completed 100 requests
Completed 200 requests
Completed 300 requests
Completed 400 requests
Completed 500 requests
Completed 600 requests
Completed 700 requests
Completed 800 requests
Completed 900 requests
Completed 1000 requests
Finished 1000 requests


Server Software:        nginx/1.24.0
Server Hostname:        www.timinglee.org
Server Port:            80

Document Path:          /static/index.html
Document Length:        153 bytes

Concurrency Level:      100
Time taken for tests:   0.084 seconds
Complete requests:      1000
Failed requests:        0
Non-2xx responses:      1000
Total transferred:      303000 bytes
HTML transferred:       153000 bytes
Requests per second:    11944.58 [#/sec] (mean)
Time per request:       8.372 [ms] (mean)
Time per request:       0.084 [ms] (mean, across all concurrent requests)
Transfer rate:          3534.38 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    4   0.9      4       6
Processing:     1    4   1.1      4       8
Waiting:        0    2   1.2      2       6
Total:          4    8   1.0      8      10

Percentage of the requests served within a certain time (ms)
  50%      8
  66%      8
  75%      9
  80%      9
  90%      9
  95%      9
  98%      9
  99%     10
 100%     10 (longest request)

Nginx的反向代理负载均衡

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

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

http upstream配置参数

#自定义一组服务器,配置在http块内

upstream name {  server ..... ...... } #示例

upstream backend {  server backend1.example.com weight=5;  server 127.0.0.1:8080  max_fails=3 fail_timeout=30s;  server unix:/tmp/backend3;  server backup1.example.com backup; } server address [parameters]; #配置一个后端web服务器,配置在upstream内,至少要有一个server服务器配置。

#server支持的parameters如下:

weight=number #设置权重,默认为1,实现类似于LVS中的WRR,WLC等

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

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

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

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

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

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

Nginx 

hash KEY [consistent]; #基于指定请求报文中首部字段或者URI等key做hash计算,使用consistent参数,将使用ketama一致性
hash算法,适用于后端是Cache服务器(如varnish)时使用,consistent定义使用一致性hash运算,一致 性hash基于取模运算

hash $request_uri consistent; 
#基于用户请求的uri做hash hash $cookie_sessionid #基于cookie中的sessionid这个key进行hash调度,实现会话绑定

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

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

 实例:

[root@apache nginx]# vim  /usr/local/nginx/conf.d/vhosts.conf
[root@apache nginx]# nginx -s reload
[root@apache nginx]# cat  /usr/local/nginx/conf.d/vhosts.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.timinglee.org;

        location / {
           proxy_pass http://webcluster;

}
[root@apache nginx]# vim  /usr/local/nginx/conf.d/vhosts.conf
[root@apache nginx]# nginx -s reload
[root@apache nginx]# cat  /usr/local/nginx/conf.d/vhosts.conf
upstream webcluster {
     ip_hash;
     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.timinglee.org;

        location / {
           proxy_pass http://webcluster;

}

[root@nginx3 ~]# route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         172.25.254.2    0.0.0.0         UG    100    0        0 eth0
172.25.254.0    0.0.0.0         255.255.255.0   U     100    0        0 eth0

实现 Nginx 四层负载均衡

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模块

官方文档:

Module ngx_stream_proxy_module

tcp负载均衡配置参数

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;    s
         erver 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;  }

}

负载均衡实例: MySQL

#在apache20中安装mysql 
[root@apache20 ~]# yum install mariadb-server -y [root@apache20 ~]# vim /etc/my.cnf.d/mariadb-server.cnf [mysqld] server-id=20 
[root@apache20 ~]# systemctl start mariadb 
[root@apache20 ~]# mysql -e "grant all on *.* to lee@'%' identified by 'lee';" 
[root@apache30 ~]# mysql -ulee -plee -h172.25.254.20 -e "select @@server_id" 
+-------------+ 
| @@server_id | 
+-------------+ 
|     20 | 
+-------------+ 
#在apache30重复以上步骤并在apache20上测试
nginx的配置
[root@Nginx ~]# vim /apps/nginx/conf/tcp/tcp.conf
stream { 
  upstream mysql_server {  
   server 172.25.254.20:3306 max_fails=3 fail_timeout=30s;      server 172.25.254.30:3306 max_fails=3 fail_timeout=30s;
   } 
  server { 
      listen 172.25.254.10:3306; 
      proxy_pass mysql_server; 
      proxy_connect_timeout 30s; 
      proxy_timeout 300s;
     } 
 } #重启nginx并访问测试:

[root@Nginx ~]# nginx -s reload 
#测试通过nginx负载连接MySQL:

[root@apache30 ~]# mysql -ulee -plee -h172.25.254.10 -e "select @@server_id" 
+-------------+ 
| @@server_id | 
+-------------+ 
|     20 | 
+-------------+ 
[root@apache30 ~]# mysql -ulee -plee -h172.25.254.10 -e "select 
@@server_id" +-------------+ 
| @@server_id |
+-------------+ 
|     30 | 
+-------------+

udp 负载均衡实例: DNS

stream {  
  upstream dns_server{  
  server 172.25.254.20:53 max_fails=3 fail_timeout=30s;       server 172.25.254.30:53 max_fails=3 fail_timeout=30s; 
   }  
server {  
   listen 172.25.254.10:53 udp;  
   proxy_pass dns_server; 
   proxy_timeout 1s; 
   proxy_responses 1; 
   # 使用UDP协议时,设置代理服务器响应客户端期望的数据报文数
   # 该值作为会话的终止条件

  error_log logs/dns.log; 
  }   
}

测试:

[root@apache30 named]# dig www.timinglee.org @172.25.254.10 

; <<>> DiG 9.16.23 <<>> www.timinglee.org @172.25.254.10 ;; global options: +cmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 33888 ;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1 ;; OPT PSEUDOSECTION: ; EDNS: version: 0, flags:; udp: 1232 ; COOKIE: 701447f1bdd8acea0100000066a27b465426b2b4bc7f1dc3 (good) ;; QUESTION SECTION: ;www.timinglee.org.       IN   A ;; ANSWER SECTION:

实现FastCGI

为什么会有FastCGI?

CGI协议虽然解决了语言解析器和 Web Server 之间通讯的问题,但是它的效率很低,因为 Web Server

每收到一个请求都会创建一个CGI进程,PHP解析器都会解析php.ini文件,初始化环境,请求结束的时候 再关闭进程,对于每一个创建的CGI进程都会执行这些操作,所以效率很低,而FastCGI是用来提高CGI性 能的,FastCGI每次处理完请求之后不会关闭掉进程,而是保留这个进程,使这个进程可以处理多个请 求。这样的话每个请求都不用再重新创建一个进程了,大大提升了处理效率。 什么是PHP-FPM?

PHP-FPM(FastCGI Process Manager:

FastCGI进程管理器)是一个实现了Fastcgi的程序,并且提供进程管理的功能。 进程包括master进程和worker进程。master进程只有一个,负责监听端口,接受来自web server

的请求

worker进程一般会有多个,每个进程中会嵌入一个PHP解析器,进行PHP代码的处理。

FastCGI配置指令

Nginx基于模块ngx_http_fastcgi_module实现通过fastcgi协议将指定的客户端请求转发至php-fpm处 理,其配置指令如下:

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 
}

FastCGI实战案例 : Nginx与php-fpm在同一服务器

重新编译nginx,保证纯洁环境:

[root@apache ~]# install gcc pcre-devel zlib-devel openssl-devel -y
[root@apache ~]# cd nginx-1.26.1/
[root@apache nginx-1.26.1]# ls
auto     CHANGES.ru  configure  html     Makefile  objs    src
CHANGES  conf        contrib    LICENSE  man       README

[root@apache nginx-1.26.1]# ./configure --prefix=/usr/local/nginx --add-module=/root/echo-nginx-module-0.63 --add-module=/root/memc-nginx-module-0.20 --add-module=/root/srcache-nginx-module-0.33 --user=nginx --with-http_v2_module --group=nginx --with-http_ssl_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@apache nginx-1.26.1]# make && make install

[root@apache nginx-1.26.1]# systemctl start nginx
[root@apache nginx-1.26.1]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@apache nginx-1.26.1]# ps aux | grep nginx
root       27826  0.0  0.0   9940   960 ?        Ss   10:33   0:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx      27827  0.0  0.1  13852  4824 ?        S    10:33   0:00 nginx: worker process
root       27926  0.0  0.0 221680  2360 pts/0    S+   10:33   0:00 grep --color=auto nginx
[root@apache nginx-1.26.1]# killall -9 nginx

[root@apache nginx-1.26.1]# ps aux | grep nginx
root       28053  0.0  0.0 221680  2348 pts/0    S+   10:33   0:00 grep --color=auto nginx

#利用yum解决php依赖

[root@Nginx ~]# yum 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 \ 

php相关配置优化

准备php测试页面

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

编译PHP:

[root@apache ~]# tar zxf php-8.3.9.tar.gz
[root@apache ~]# ls
公共  anaconda-ks.cfg                nginx-1.24.0.tar.gz
模板  cert                           nginx-1.26.1
视频  echo-nginx-module-0.63         nginx-1.26.1.tar.gz
图片  echo-nginx-module-0.63.tar.gz  nnn.jpg
文档  memc-nginx-module-0.20         php-8.3.9
下载  memc-nginx-module-0.20.tar.gz  php-8.3.9.tar.gz
音乐  mnt                            srcache-nginx-module-0.33
桌面  nginx-1.24.0                   srcache-nginx-module-0.33.tar.gz

[root@apache ~]# tar zxf openresty-1.25.3.1.tar.gz
[root@apache ~]# yum install -y bzip2 systemd-devel libxml2-devel sqlite-devel
libpng-devel libcurl-devel oniguruma-devel

bash: libpng-devel: command not found...
[root@apache ~]# dnf install libpng-devel -y   #解决依赖

[root@apache ~]# cd php-8.3.9/
[root@apache php-8.3.9]# ./configure --prefix=/usr/local/php --with-config-file-path=/usr/local/php/etc \--enable-fpm \--with-fpm-user=nginx \--with-fpm-group=nginx \--with-curl \--with-iconv --with-mhash\--with-zlib\--with-openssl\--enable-mysqlnd\--with-mysqli \--with-pdo-mysql\--disable-debug \--enable-sockets \--enable-xml \--enable-ftp \--enable-gd \--enable-exif \--enable-mbstring \--enable-bcmath \--with-fpm-systemd

[root@apache php-8.3.9]# dnf install -y  libcurl-devel
[root@apache php-8.3.9]# wget https://mirrors.aliyun.com/rockylinux/9.4/devel/x86_64/kickstart/Packages/o/oniguruma-devel-6.9.6-1.el9.5.x86_64.rpm
[root@apache php-8.3.9]# yum install oniguruma-devel-6.9.6-1.el9.5.x86_64.rpm -y

每次下载一次软件包都得重新编译,直到没有错误,才能make:
[root@apache php-8.3.9]# ./configure --prefix=/usr/local/php --with-config-file-path=/usr/local/php/etc \--enable-fpm \--with-fpm-user=nginx \--with-fpm-group=nginx \--with-curl \--with-iconv --with-mhash\--with-zlib\--with-openssl\--enable-mysqlnd\--with-mysqli \--with-pdo-mysql\--disable-debug \--enable-sockets \--enable-xml \--enable-ftp \--enable-gd \--enable-exif \--enable-mbstring \--enable-bcmath \--with-fpm-systemd

[root@apache php-8.3.9]# make && make install
[root@apache php-8.3.9]# cd /usr/local/php/etc/
[root@apache etc]# ls
php-fpm.conf.default  php-fpm.d
[root@apache etc]# cp -p php-fpm.conf.default php-fpm.conf
[root@apache etc]# vim  php-fpm.conf
去掉注释
pid = run/php-fpm.pid #指定pid文件存放位置


[root@apache etc]# cd php-fpm.d/
[root@apache php-fpm.d]# ls
www.conf.default
[root@apache php-fpm.d]# cp www.conf.default  www.conf -p
[root@apache php-fpm.d]# vim www.conf


#生成主配置文件
[root@apache php-8.3.9]# cp php.ini-production  /usr/local/php/etc/php.ini
[root@apache php-8.3.9]# cd
[root@apache ~]# cd /usr/local/php/etc
[root@apache etc]# ls
php-fpm.conf  php-fpm.conf.default  php-fpm.d  php.ini
[root@apache etc]# vim php.ini

[Date]
; Defines the default timezone used by the date functions
; https://php.net/date.timezone
date.timezone = Asia/Shanghai #修改时区


#生成启动文件
[root@apache ~]# cd /root/php-8.3.9/sapi/fpm/
[root@apache fpm]# ls
config.m4       init.d.php-fpm.in  php-fpm.8        php-fpm.service     tests
CREDITS         LICENSE            php-fpm.8.in     php-fpm.service.in  www.conf
fpm             Makefile.frag      php-fpm.conf     status.html         www.conf.in
init.d.php-fpm  php-fpm            php-fpm.conf.in  status.html.in
[root@apache fpm]# cp php-fpm.service /lib/systemd/system/
[root@apache fpm]# systemctl daemon-reload
[root@apache 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@apache fpm]# systemctl daemon-reload
[root@apache fpm]# systemctl start php-fpm

[root@apache fpm]# netstat -antlupe | grep php
tcp        0      0 127.0.0.1:9000          0.0.0.0:*               LISTEN      0          226866     245498/php-fpm: mas

#添加PHP环境变量:
[root@apache fpm]# cd /usr/local/php/bin
[root@apache bin]# vim ~/.bash_profile
[root@apache bin]# source  ~/.bash_profile

准备PHP测试页面:

[root@apache bin]# mkdir -p /data/web/php
[root@apache bin]# cd /data/web/php
[root@apache php]# vim index.php
[root@apache php]# cat index.php
<?php
  phpinfo();
?>

php的动态扩展模块

[root@apache ~]# tar zxf memcache-8.2.tgz
[root@apache ~]# cd memcache-8.2/
[root@apache memcache-8.2]# yum install autoconf
[root@apache memcache-8.2]# phpize
Configuring for:
PHP Api Version:         20230831
Zend Module Api No:      20230831
Zend Extension Api No:   420230831
[root@nginx memcache-8.2]# ./configure && make && make install
[root@nginx memcache-8.2]# cd /usr/local/php/lib/php/extensions/no-debug-non-zts-20230831/
[root@nginx no-debug-non-zts-20230831]# ls
memcache.so  opcache.so

[root@nginx ~]# vim /usr/local/php/etc/php.ini
[root@nginx ~]# systemctl restart php-fpm.service
[root@nginx ~]# php -m
[PHP Modules]
#主要是这个
memcache
[root@nginx ~]# yum install memcached -y
[root@nginx ~]# vim /etc/sysconfig/memcached
[root@nginx ~]# cat /etc/sysconfig/memcached
PORT="11211"
USER="memcached"
MAXCONN="1024"
CACHESIZE="64"
OPTIONS="-l 127.0.0.1,::1"

[root@nginx ~]# systemctl start memcached.service

[root@nginx ~]# cd memcache-8.2/
[root@nginx memcache-8.2]# cp example.php  memcache.php /data/web/php/


[root@nginx memcache-8.2]# vim memcache.php

[root@nginx memcache-8.2]# ab -n1000 -c 10 http://www.timinglee.org/index.php

性能对比:
[root@apache20 ~]# ab -n500 -c10 http://php.timinglee.org/index.php 

@@@内容忽略@@@ 
Concurrency Level:   10 
Time taken for tests:  0.514 seconds 
Complete requests:   500 
Failed requests:    44  
   (Connect: 0, Receive: 0, Length: 44, Exceptions: 0) [root@apache20 ~]# ab -n500 -c10 http://php.timinglee.org/example.php 
 @@@内容忽略@@@ 
 Concurrency Level:   10 
 Time taken for tests:  0.452 
 seconds Complete requests:   500 
 Failed requests:    0

php高速缓存

部署方法 在我们安装的nginx中默认不支持memc和srcache功能,需要借助第三方模块来让nginx支持此功能,所 以nginx需要重新编译

[root@nginx memcache-8.2]# cd /usr/local/nginxconf.d/
[root@nginx conf.d]# ls
vhosts.conf
[root@nginx conf.d]# vim vhosts.conf
[root@nginx conf.d]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@nginx conf.d]# cat vhosts.conf
upstream memcache {
   server 127.0.0.1:11211;
   keepalive 512;
}
server {
    listen 80;
    server_name www.timinglee.org;
    root /data/web/html;
    index index.html;

    location /memc {
        internal;
        memec_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$ {
    root /data/web/php;
    set $key $uri$args;
    srcchace_pass GET /memc $key;
    srcchace_store PUT /memc $key;
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    include fastcgi.conf;
 }

}

[root@nginx conf.d]# nginx -s reload
[root@nginx conf.d]# ab -n1000 -c 10 http://www.timinglee.org/index.php
Concurrency Level:     10
Time taken for tests:   0.255 seconds
Complete requests:     500
Failed requests:       0

nginx 二次开发版本

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是个不错的选择

官网: OpenResty® - 开源官方站

编译安装 openresty:
[root@nginx ~]# cd openresty-1.25.3.1/
[root@nginx openresty-1.25.3.1]# ./configure --prefix=/usr/local/openresty \

> --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 openresty-1.25.3.1]#
make && make install
[root@Nginx openresty-1.25.3.1]#ln -s /apps/openresty/bin/* /usr/bin/
[root@Nginx openresty-1.25.3.1]#openresty -v
nginx version: openresty/1.25.3.1
[root@Nginx openresty-1.25.3.1]#openresty 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值