企业高性能web服务器

1. Nginx 安装

1.1 Nginx版本和安装方式

Nginx版本

  • Mainline version 主要开发版本,一般为奇数版本号,比如1.19
  • Stable version 当前最新稳定版,一般为偶数版本,如:1.20
  • Legacy versions 旧的稳定版,一般为偶数版本,如:1.18

Nginx安装可以使用yum或源码安装,但是推荐使用源码编译安装

  • yum的版本比较旧
  • 编译安装可以更方便自定义相关路径
  • 使用源码编译可以自定义相关功能,更方便业务的上的使用

1.1.1编译安装 Nginx

官方源码包下载地址:

https://nginx.org/en/download.html

编译安装示例:

[root@Nginx ~]# dnf install gcc pcre-devel zlib-devel openssl-devel -y
 [root@Nginx nginx-1.24.0]# useradd  -s /sbin/nologin -M nginx
 [root@Nginx nginx]# tar zxf nginx-1.24.0.tar.gz
 [root@Nginx nginx-1.24.0]# useradd  -s /sbin/nologin -M nginx
 [root@Nginx nginx]# cd nginx-1.24.0/
 [root@Nginx nginx-1.24.0]# ls
 auto     
CHANGES.ru  configure  html     
CHANGES  conf        
contrib    
Makefile  objs    
LICENSE  man       
[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         
# 指定nginx运行用户
# 指定nginx运行组
# 支持https://
 # 支持http版本2
 # 支持ip透传
# 支持状态页面    
# 支持压缩  
# 支持正则
# 支持tcp反向代理
# 支持tcp的ssl加密
# 支持tcp的透传ip
 [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二进制启动脚本,可以接受不同的参数以实现不同的功能。

1.1.2 验证版本及编译参数

[root@Nginx ~]# vim ~/.bash_profile
 export PATH=$PATH:/usr/local/nginx/sbin
 [root@Nginx ~]# source  ~/.bash_profile
 [root@Nginx ~]# nginx -V
 nginx version: nginx/1.24.0
 built by gcc 11.4.1 20231218 (Red Hat 11.4.1-3) (GCC)
 built with OpenSSL 3.0.7 1 Nov 2022
 TLS SNI support enabled
 configure arguments: --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

1.1.3 使用安装完成的二进制文件nginx

[root@Nginx ~]# nginx -v
 nginx version: nginx/1.18.0
 Usage: nginx [-?hvVtTq] [-s signal] [-c filename] [-p prefix] [-g directives]
 Options:-?,-h         -v           -V           -t           -T           -q           
模式-s signal     
: this help
 : show version and exit
 : show version and configure options then exit     
: test configuration and exit                      
: test configuration, dump it and exit             
发送信号,reload信号 会生成新的worker,但master不会重新生成-p prefix     
配置文件路径
#显示版本和编译参数
#测试配置文件是否异
#测试并打印
: suppress non-error messages during configuration testing     
: send signal to a master process: stop, quit, reopen, reload     
: set prefix path (default: /etc/nginx/)          
#静默
#指定Nginx 目录-c filename   : set configuration file (default: /etc/nginx/nginx.conf)         
#
 #-g directives : set global directives out of configuration file #设置全局指令,注意和
配置文件不要同时配置,否则冲突

1.1.4 Nginx 启动文件

 [root@Nginx ~]# vim /lib/systemd/system/nginx.service
 [root@Nginx ~]# systemctl daemon-reload
 [root@Nginx ~]# systemctl start nginx 

1.2 平滑升级和回滚

有时候我们需要对Nginx版本进行升级以满足对其功能的需求,例如添加新模块,需要新功能,而此时 Nginx又在跑着业务无法停掉,这时我们就可能选择平滑升级

1.2.1 平滑升级流程

  • 将旧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

1.2.2 平滑升级和回滚案例

[root@Nginx nginx]# tar zxf nginx-1.26.1.tar.gz
[root@Nginx nginx]# cd nginx-1.26.1/

开始编译

[root@Nginx nginx-1.26.1]# ./configure --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.26.1]# make

查看版本

[root@Nginx nginx-1.26.1]# ll  objs/nginx /usr/local/nginx/sbin/nginx-rwxr-xr-x 1 root root 1239416 Jul 18 15:08 objs/nginx-rwxr-xr-x 1 root root 5671488 Jul 18 11:41 /usr/local/nginx/sbin/nginx

将之前的旧版nginx命令备份

[root@Nginx ~]# cd /usr/local/nginx/sbin/
[root@Nginx sbin]# cp nginx nginx.24

将新版本的nginx命令复制过去

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

 [root@Nginx sbin]# kill -USR2 48732 #nginx worker ID
 #USR2 平滑升级可执行程序,将存储有旧版本主进程PID的文件重命名为nginx.pid.oldbin,并启动新的
nginx
 #此时两个master的进程都在运行,只是旧的master不在监听,由新的master监听80
 #此时Nginx开启一个新的master进程,这个master进程会生成新的worker进程,这就是升级后的Nginx进
程,此时老的进程不会自动退出,但是当接收到新的请求不作处理而是交给新的进程处理。

 [root@Nginx sbin]# curl -I  localhost
 HTTP/1.1 200 OK
 Server: nginx/1.24.0                
Ss   
S    
S    
S    
##依旧是旧版本生生效
Date: Thu, 18 Jul 2024 07:45:58 GMT
 Content-Type: text/html
 Content-Length: 615
 Last-Modified: Thu, 18 Jul 2024 03:41:13 GMT
 Connection: keep-alive
 ETag: "66988ed9-267"
 Accept-Ranges: bytes
 #回收旧版本
[root@Nginx sbin]# kill -WINCH 48732
 [root@Nginx sbin]# ps aux | grep nginx
 root       
48732  0.0  0.1   9868  2436 ?        
process /usr/local/nginx/sbin/nginx
 root       
52075  0.0  0.3   9876  6528 ?        
Ss   
S    
14:17   
14:17   
15:41   
15:41   
14:17   
15:41   
0:00 nginx: master 
0:00 nginx: worker 
0:00 nginx: master 
0:00 nginx: worker 
0:00 nginx: master 
0:00 nginx: master 
process /usr/local/nginx/sbin/nginx
nobody     
process
 52076  0.0  0.2  14208  4868 ?        
#检测版本信息
[root@Nginx sbin]# curl  -I localhost
 HTTP/1.1 200 OK
 Server: nginx/1.26.1                    
Date: Thu, 18 Jul 2024 07:59:45 GMT
 Content-Type: text/html
 Content-Length: 615
 Last-Modified: Thu, 18 Jul 2024 03:41:13 GMT
 Connection: keep-alive
 ETag: "66988ed9-267"
 Accept-Ranges: bytes

回滚

如果升级的版本发现问题,可以重新拉起之前的旧版本

 [root@Nginx sbin]# cp nginx nginx.26
 [root@Nginx sbin]# ls
 nginx  nginx.24  nginx.26
 [root@Nginx sbin]# mv nginx.24 nginx
 mv: overwrite 'nginx'? y
 [root@Nginx sbin]# kill -HUP 48732
 [root@Nginx sbin]# ps aux | grep nginx
 root       
48732  0.0  0.1   9868  2436 ?        
process /usr/local/nginx/sbin/nginx
 root       
52075  0.0  0.3   9876  6528 ?        
process /usr/local/nginx/sbin/nginx
 nobody     
52076  0.0  0.2  14208  5124 ?        
process
 nobody     
process
 52130  0.0  0.2  14200  4868 ?        
[root@Nginx sbin]# kill -WINCH 52075
 [root@Nginx sbin]# ps aux | grep nginx
 root       
48732  0.0  0.1   9868  2436 ?        
process /usr/local/nginx/sbin/nginx
 root       
52075  0.0  0.3   9876  6528 ?        
process /usr/local/nginx/sbin/nginx
 nobody     
process
 root       
15:41   
0:00 nginx: worker 
Ss   
S    
S    
S    
Ss   
S    
52130  0.0  0.2  14200  4868 ?        
52137  0.0  0.1 221664  2176 pts/0    
color=auto nginx
 [root@Nginx sbin]# curl  -I  localhost
 HTTP/1.1 200 OK
 Server: nginx/1.24.0                        
S    
S+   
14:17   
15:41   
15:41   
16:30   
14:17   
15:41   
16:30   
16:31   
##版本回滚完成
Date: Thu, 18 Jul 2024 08:31:51 GMT
 Content-Type: text/html
 Content-Length: 615
 Last-Modified: Thu, 18 Jul 2024 03:41:13 GMT
 Connection: keep-alive
 ETag: "66988ed9-267"
 Accept-Ranges: bytes

2. Nginx 核心配置详解

nginx 官方帮助文档: http://nginx.org/en/docs/

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

  • 主配置文件:nginx.conf 子
  • 配置文件: include conf.d/*.conf
  • fastcgi, uwsgi,scgi 等协议相关的配置文件
  • mime.types:支持的mime类型,MIME(Multipurpose Internet Mail Extensions)多用途互联网邮 件扩展类型,MIME消息能包含文本、图像、音频、视频以及其他应用程序专用的数据,是设定某种扩展名的文件用一种应用程序来打开的方式类型,当该扩展名文件被访问的时候,浏览器会自动 使用指定应用程序来打开。多用于指定一些客户端自定义的文件名,以及一些媒体文件打开方式

2.1 新建一个 PC web 站点

#定义子配置文件路径
[root@Nginx ~]# mkdir  /usr/local/nginx/conf.d/
 [root@centos8 ~]# vim /usr/local/nginx/conf/nginx.conf
 http {
 ......
 include /apps/nginx/conf/conf.d/*.conf;     
生效
}
 #创建虚拟主机网站配置
[root@Nginx ~]# vim /usr/local/nginx/conf.d/vhosts.conf
 server {
 listen 80;
 server_name lee.xiaozhou.org;
 location / {
 root /webdata/nginx/xiaozhou.org/lee/html;
 }
 }
 #在配置文件的最后面添加此行
#注意不要放在最前面,会导致前面的命令无法
[root@Nginx ~]# mkdir  -p /webdata/nginx/xiaozhou.org/lee/html
 [root@Nginx ~]# echo lee.xiaozhou.org > 
/webdata/nginx/xiaozhou.org/lee/html/index.html
 [root@Nginx ~]# nginx -s reload
 #访问测试
[root@node100 ~]# curl  lee.xiaozhou.org           
lee.xiaozhou.org

2.2 root 与 alias

  • root:指定web的家目录,在定义location的时候,文件的绝对路径等于 root+location
  • alias:定义路径别名,会把访问的路径重新定义到其指定的路径,文档映射的另一种机制;仅能用于 location上下文,此指令使用较少

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

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

2.3 Nginx 账户认证功能

由 ngx_http_auth_basic_module 模块提供此功能

示例:

[root@Nginx ~]# htpasswd  -cmb /usr/local/nginx/conf/.htpasswd admin lee   #-b 表
示非交互建立用户认证
Adding password for user admin
 [root@Nginx ~]# htpasswd  -mb /usr/local/nginx/conf/.htpasswd lee lee
 Adding password for user lee
 [root@Nginx ~]# cat /usr/local/nginx/conf/.htpasswd
 admin:$apr1$haGCKgCT$myogggALmqNecTyNupsWQ/
 lee:$apr1$H97AyQPF$kGU.Tc4zn1E4Zkp/M4R6G.
 }
 [root@Nginx ~]# mkdir  /webdata/nginx/timinglee.org/lee/login
 [root@Nginx ~]# echo login > /webdata/nginx/timinglee.org/lee/login/index.html
 [root@Nginx ~]# vim /usr/local/nginx/conf.d/vhosts.conf
 server {
 listen 80;
 server_name lee.timinglee.org;
 location /login {
 root /webdata/nginx/timinglee.org/lee;
 index index.html;
 auth_basic  "login password";
 auth_basic_user_file "/usr/local/nginx/conf/.htpasswd";
 }
 #重启Nginx并访问测试
[root@node100 ~]# curl  lee.timinglee.org/login/ -u lee:lee
 login
 [root@node100 ~]# curl  lee.timinglee.org/login/ -u admin:lee
 login

2.4 自定义错误页面

自定义错误页,同时也可以用指定的响应状态码进行响应, 可用位置:http, server, location, if in location

[root@Nginx ~]# mkdir /webdata/nginx/timinglee/lee/errors -p
 [root@Nginx ~]# echo error page > /webdata/nginx/timinglee/lee/errors/40x.html
 server {
 listen 80;
 server_name lee.timinglee.org;
 error_page 404 /40x.html
 location = /40x.html {
 root /webdata/nginx/timinglee/lee/errors;
 }
 }
测试:
[root@node100 ~]# curl  lee.timinglee.org/haha
 error page

2.5 自定义错误日志

server {
        listen 80;
        server_name lee.xiaozhou.org;
        error_page 404 /40x.html;
        access_log /var/log/nginx/access.log;
        errog_log  /var/log/nginx/error/log;

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

2.6 检测文件是否存在

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

示例: 如果不存在页面, 就转到default.html页

[root@Nginx ~]# echo "index.html is not exist" > 
/webdata/nginx/timinglee.org/lee/error/default.html
 [root@Nginx ~]# vim /usr/local/nginx/conf.d/vhosts.conf
 server {
 listen 80;
 server_name lee.timinglee.org;
 root /webdata/nginx/timinglee.org/lee;
 error_page 404 /40x.html;
 access_log /var/log/nginx/access.log;
 error_log  /var/log/nginx/error.log;
 try_files $uri $uri.html $uri/index.html /error/default.html;
 location = /40x.html {
 root /webdata/nginx/timinglee/lee/errors;
 }
 }

2.7 作为下载服务器配置

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

示例:实现下载站点

[root@Nginx ~]# mkdir -p /data/web/xiaozhou.org/lee/download
 [root@Nginx ~]# cp /root/anaconda-ks.cfg 
/data/web/xiaozhou.org/lee/download
 [root@Nginx ~]# vim /usr/local/nginx/conf.d/vhosts.conf
 server {
 listen 80;
 server_name lee.xiaozhou.org;
 root /data/web/xiaozhoug.org/lee;
 access_log /var/log/nginx/access.log;
 error_log  /var/log/nginx/error.log;
 try_files $uri $uri.html $uri/index.html /error/default.html;
 location = /40x.html {
 root /data/web/xiaozhoug.org/lee/errors;
 }
 location /download {
 autoindex on;               
autoindex_exact_size on;    
#自动索引功能
#计算文件确切大小(单位bytes),此为默认值,off只显示示GMT时间
大概大小(单位kb、mb、gb)
autoindex_localtime on; 
}
 limit_rate 1024k;               #on表示显示本机时间而非GMT(格林威治)时间,默为为off显
#限速,默认不限速    }            #重启Nginx并访问测试下载页面

3. Nginx 高级配置

3.1 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:         
accepts:                    
handled:                    
连接
requests:                   
#当前处于活动状态的客户端连接数
#包括连接等待空闲连接数=reading+writing+waiting
 #统计总值,Nginx自启动后已经接受的客户端请求连接的总数。
#统计总值,Nginx自启动后已经处理完成的客户端请求连接总数
#通常等于accepts,除非有因worker_connections限制等被拒绝的
#统计总值,Nginx自启动后客户端发来的总的请求数
Reading:                    
Writing:                    
访问量很大
Waiting:                    
#当前状态,正在读取客户端请求报文首部的连接的连接数
#数值越大,说明排队现象严重,性能不足
#当前状态,正在向客户端发送响应报文过程中的连接数,数值越大,说明
#当前状态,正在等待客户端发出请求的空闲连接数
开启 keep-alive的情况下,这个值等于active -- 
(reading+writing

3.2 Nginx 压缩功能

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

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

配置指令如下:

[root@Nginx ~]# mkdir  /webdata/nginx/timinglee.org/lee/data
 [root@Nginx ~]# cp /usr/local/nginx/logs/access.log 
/webdata/nginx/timinglee.org/lee/data/data.txt
 [root@Nginx ~]# echo test > /webdata/nginx/timinglee.org/lee/data/test.html     
小于1k的文件测试是否会压缩
[root@Nginx ~]# vim /usr/local/nginx/conf/nginx.conf

 gzip on;
 gzip_comp_level 5;
 gzip_min_length 1k;
 gzip_types text/plain application/javascript application/x-javascript text/css  
application/xml text/javascript application/x-httpd-php image/gif image/png;   
gzip_vary on;
 #重启Nginx并访问测试:
[root@client ~]# curl --head --compressed lee.timinglee.org/data/test.html
 HTTP/1.1 200 OK
 Server: nginx/1.26.1
 Date: Sun, 21 Jul 2024 15:42:46 GMT
 Content-Type: text/html
 Content-Length: 5
 Last-Modified: Sun, 21 Jul 2024 15:40:35 GMT
 Connection: keep-alive
 ETag: "669d2bf3-5"
 Accept-Ranges: bytes
 [root@client ~]# curl --head --compressed lee.timinglee.org/data/data.txt
 HTTP/1.1 200 OK
 Server: nginx/1.26.1
 Date: Sun, 21 Jul 2024 15:43:17 GMT
 Content-Type: text/plain
 Last-Modified: Sun, 21 Jul 2024 15:40:13 GMT
 Connection: keep-alive
 Vary: Accept-Encoding
 ETag: W/"669d2bdd-3e25b5"
 Content-Encoding: gzip

3.3 nginx变量

3.3.1 常用内置变量

$remote_addr; 
#存放了客户端的地址,注意是客户端的公网IP
 $args; 
#变量中存放了URL中的所有参数
#例如:https://search.jd.com/Search?keyword=手机&enc=utf-8
 #返回结果为: keyword=手机&enc=utf-8
 $is_args
 #如果有参数为? 否则为空
$document_root; 
#保存了针对当前资源的请求的系统根目录,例如:/webdata/nginx/timinglee.org/lee。
$document_uri;
 #保存了当前请求中不包含参数的URI,注意是不包含请求的指令
#比如:http://lee.timinglee.org/var?\id=11111会被定义为/var 
#返回结果为:/var
 $host; 
#存放了请求的host名称
limit_rate 10240;
 echo $limit_rate;
 #如果nginx服务器使用limit_rate配置了显示网络速率,则会显示,如果没有设置, 则显示0
 $remote_port;
 #客户端请求Nginx服务器时随机打开的端口,这是每个客户端自己的端口
$remote_user;
 #已经经过Auth Basic Module验证的用户名
$request_body_file;
 #做反向代理时发给后端服务器的本地资源的名称
$request_method;
#请求资源的方式,GET/PUT/DELETE等
$request_filename;
 #当前请求的资源文件的磁盘路径,由root或alias指令与URI请求生成的文件绝对路径,
#如:webdata/nginx/timinglee.org/lee/var/index.html
 $request_uri;
 #包含请求参数的原始URI,不包含主机名,相当于:$document_uri?$args,
 #例如:/main/index.do?id=20190221&partner=search 
$scheme;
 #请求的协议,例如:http,https,ftp等
$server_protocol;
 #保存了客户端请求资源使用的协议的版本,例如:HTTP/1.0,HTTP/1.1,HTTP/2.0等
$server_addr;
 #保存了服务器的IP地址
$server_name;
 #虚拟主机的主机名
$server_port;
 #虚拟主机的端口号
$http_user_agent;
 #客户端浏览器的详细信息
$http_cookie;
 #客户端的所有cookie信息
$cookie_<name>
 #name为任意请求报文首部字部cookie的key名

3.3.2 自定义变量

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

语法格式:

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

4. Nginx Rewrite 相关功能

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

4.1 if 指令

if (条件匹配) { 
action
 }

使用正则表达式对变量进行匹配,匹配成功时if指令认为条件为true,否则认为false

4.2 set 指令

指定key并给其定义一个变量,变量可以调用Nginx内置变量赋值给key

另外set定义格式为set $key value,value可以是text, variables和两者的组合。

4.3 break 指令

用于中断当前相同作用域(location)中的其他Nginx配置

与该指令处于同一作用域的Nginx配置中,位于它前面的配置生效

位于后面的 ngx_http_rewrite_module 模块中指令就不再执行

Nginx服务器在根据配置处理请求的过程中遇到该指令的时候,回到上一层作用域继续向下读取配置,、 该指令可以在server块和locationif块中使用

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

例如:

[root@Nginx ~]# vim /usr/local/nginx/conf.d/vhosts.conf
 server {
 listen 80;
 server_name lee.timinglee.org;
 root /webdata/nginx/timinglee.org/lee;
 location /break{
 default_type text/html;
 set $name lee;
 echo $name;
 break;
 set $port $server_port;
 echo $port;
 }
 }

测试:

[root@client ~]# curl  lee.timinglee.org/break          
lee
 80
 [root@client ~]# curl  lee.timinglee.org/break          
lee

4.4 全站加密

[root@Nginx ~]# mkdir /usr/local/nginx/certs					创建文件放加密文件

[root@Nginx ~]# openssl req -newkey  rsa:2048 -nodes -sha256 -keyout /usr/local/nginx/certs/xiaozhou.org.key \
-x509  -days 365 -out /usr/local/nginx/certs/xiaozhou.org.crt       创建加密

[root@Nginx ~]# vim /usr/local/nginx/con.d/vhosts.conf      创建配置文件

server {
    listen 80;                      监听端口80
    listen 443 ssl;					ssl加密走443
    server_name www.xiaozhou.org;	域名www.xiaozhou.org
    root /data/web/html;			发布目录为   /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 ){            如果访问/时不是http的话走下边
            rewrite / https://$host/$1 redirect;	
        	}
    	if ( !-e $request_filename ){	  如果(!-e)文件不存在  走下边
            rewrite /(.*) https://$host/index.html redirect;
    	}
    }
}

测试

4.5 防盗链

对端httpd配置:

[root@nginx2 ~]# vim /var/www/html/index.html
<html>

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

  <body>
    <img src="http://www.xiaozhou.org/images/xiaotong.jpg" >
    <h1 style="color:red">欢迎大家</h1>
    <p><a href=http://www.xiaozhou.org>小彤</a>出门见喜</p>
  </body>

</html>

没做防盗链时对端会盗取本机的web发布资源(172.25.254.200为对端ip)

本机配置(禁止全站/禁止部分 自由选择)

server {
    listen 80;
    listen 443 ssl;
    server_name www.timinglee.org;
    root /data/web/html;
    index index.html;
    ssl_certificate /usr/local/nginx/certs/xiaozhou.org.crt;
    ssl_certificate_key /usr/local/nginx/certs/xiaozhou.org.key;
    ssl_session_cache    shared:SSL:1m;
    ssl_session_timeout  5m;

location /{    (/  禁止全站)  (/images  禁止)           
        valid_referers none blocked server_names  *.xiaozhou.org~/.baidu/.;
        		   允许已上
        		   
        if ($invalid_referer){       
                rewrite ^/   http://www.xiaozhou.org/dog.jpg;
                }
        }
}

5. Nginx 反向代理功能

5.1 指定 location 实现反向代理

针对指定的 location

server {
 listen 80;
 server_name www.timinglee.org;
 location / {
 proxy_pass http://172.25.254.100;
 }
 location ~ /static {
 proxy_pass http://172.25.254.30:8080;
 }
 }

后端web服务器必须要有相对于的访问URL

[root@apache100 ~]# mkdir  /var/www/html/static
[root@apache100 ~]# echo static 172.25.254.100 > /var/www/html/static/index.html

 [root@apache30 ~]# echo 172.25.254.30 > /var/www/html/index.html

重启Nginx并访问测试:

 curl www.timinglee.org/static/
 static 172.25.254.100

curl www.timinglee.org
 172.25.254.30

5.2 反向代理示例: 缓存功能

5.2.1 非缓存场景压测

#准备后端httpd服务器
[root@apache20 app1]# pwd
 /var/www/html/static
 [root@apache20 static]# cat /var/log/messages > ./log.html #准备测试页面
[root@apache30 ~]# ab -n1000 -c100  http://www.timinglee.org/static/index.html
Concurrency Level:      100
 Time taken for tests:   23.238 seconds
 Complete requests:      1000
 Failed requests:        0
Total transferred:      2011251000 bytes
HTML transferred:       2010991000 bytes
Requests per second:    43.03 [#/sec] (mean)
Time per request:       2323.789 [ms] (mean)
Time per request:       23.238 [ms] (mean, across all concurrent requests)
 Transfer rate:          84521.97 [Kbytes/sec] received

5.2.2 准备缓存配置

 [root@Nginx ~]# vim /apps/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@Nginx ~]# vim /apps/nginx/conf.d/vhost.conf
 location ~ /static {      
#要缓存的URL 或者放在server配置项对所有URL都进行缓存
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;    
}
 #必须指定哪些响应码的缓存
#/data/nginx/proxycache/ 目录会自动生成
[root@Nginx ~]# ll /apps/nginx/proxy_cache/ -d
 drwx------ 3 nginx root 4096  7月 25 20:07 /apps/nginx/proxy_cache/
 [root@Nginx ~]# tree /apps/nginx/proxy_cache/
 /data/nginx/proxycache/
 0 directories, 0 files

5.2.3 验证

[root@apache30 ~]# ab -n1000 -c100  http://www.timinglee.org/static/index.html
 [root@centos8 ~]# ab -n 2000 -c200 http://www.magedu.org/static/log.html    
Concurrency Level:       100
 Time taken for tests:   10.535 seconds
 Complete requests:      1000
 Failed requests:        0
Total transferred:       2011251000 bytes
HTML transferred:        2010991000 bytes
Requests per second:     94.92 [#/sec] (mean)
Time per request:        1053.507 [ms] (mean)
Time per request:        10.535 [ms] (mean, across all concurrent requests)
Transfer rate:           186435.60 [Kbytes/sec] received

[root@Nginx ~]# tree /apps/nginx/proxy_cache/
 /apps/nginx/proxy_cache/
 └── e
 └── 50
 └── 99
 └── 319432ef3663735a9d3cb4e0c1d9950e
 3 directories, 0 files

5.3 http 反向代理负载均衡

基于Cookie 实现会话绑定

[root@Nginx ~]# vim  /apps/nginx/conf.d/vhost.conf
 http {
 upstream websrvs {
 hash $cookie_hello;  #hello是cookie的key的名称
server 10.0.0.101:80 weight=2;
 server 10.0.0.102:80 weight-1;
 }
 }
 [root@centos8 ~]# vim /apps/nginx/conf/conf.d/pc.conf
 upstream webserver {
 #ip_hash;
 #hash $request_uri consistent;
 hash $cookie_lee;
 #least_conn;
 server 172.25.254.20:8080 weight=1 fail_timeout=15s max_fails=3;
 server 172.25.254.30:80 weight=1 fail_timeout=15s max_fails=3;
 #server 172.25.254.10:80 backup;
 }
 server {
 listen 80;
 server_name www.timinglee.org;
 location ~ / {
proxy_pass http://webserver;
 }
 }

5.4 实现 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模块

5.5 负载均衡实例: MySQL

后端服务器安装 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 |
 +-------------+

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

测试:

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

5.6 实现 FastCGI

什么是PHP-FPM?

PHP-FPM(FastCGI Process Manager:

  • FastCGI进程管理器)是一个实现了Fastcgi的程序,并且提供进程管理的功能。

  • 进程包括master进程和worker进程。master进程只有一个,负责监听端口,接受来自web server 的请求

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

    [root@Nginx ~]# ./configure --prefix=/usr/local/php \ --enable-fpm \ --with-iconv \
    #利用yum解决php依赖
    [root@Nginx ~]# yum install -y bzip2 systemd-devel libxml2-devel sqlite-devel
    libpng-devel libcurl-devel oniguruma-devel
    --with-config-file-path=/usr/local/php/etc \
    --with-fpm-user=nginx \ --with-fpm-group=nginx --with-curl \ --with-mhash \ --with-zlib \ --with-openssl \ --enable-mysqlnd \
    --with-mysqli \
    --with-pdo-mysql --disable-debug \ --enable-sockets \ --enable-soap \ --enable-xml \ --enable-ftp \ --enable-gd \ --enable-exif \ --enable-mbstring \ --enable-bcmath \

php相关配置优化

 [root@Nginx ~]# cd /usr/local/php/etc
 [root@Nginx etc]# cp php-fpm.conf.default php-fpm.conf
 [root@Nginx etc]# vim php-fpm.conf
去掉注释
pid = run/php-fpm.pid       
#指定pid文件存放位置
[root@Nginx etc]# cd php-fpm.d/
 [root@Nginx  php-fpm.d]# cp www.conf.default www.conf
 #生成主配置文件
[root@Nginx php-fpm.d]# cd /root/php-8.3.9/
 [root@Nginx php-8.3.9]# cp php.ini-production /usr/local/php/etc/php.ini
 [root@Nginx ~]# vim /usr/local/php/etc/php.ini
 [Date]
 ; Defines the default timezone used by the date functions
 ; https://php.net/date.timezone
 date.timezone = Asia/Shanghai       
#修改时区

生成启动文件

[root@Nginx ~]# cd /root/php-8.3.9/
 [root@Nginx php-8.3.9]# cp sapi/fpm/php-fpm.service /lib/systemd/system/
 # Mounts the /usr, /boot, and /etc directories read-only for processes invoked by 
this unit.
 #ProtectSystem=full         
#注释该内容

查看

[root@Nginx php-8.3.9]# systemctl start php-fpm.service
 [root@Nginx php-8.3.9]# netstat -antlupe | grep php

准备php测试页面

[root@Nginx ~]# mkdir  /data/php -p
 [root@centos8 ~]# cat /data/php/index.php #php测试页面
<?php
 phpinfo();
 ?>

Nginx配置转发

[root@Nginx ~]# vim /apps/nginx/conf.d/php.conf
 server {
 listen 80;
 server_name php.timinglee.org;
 root /data/php;
 location ~ \.php$ {
 fastcgi_pass 127.0.0.1:9000;
 fastcgi_index index.php;
 include fastcgi.conf;
 }
 }
 #重启Nginx并访问web测试
[root@Nginx ~]# nginx -s reload

添加php环境变量

[root@Nginx ~]# vim .bash_profile
 # .bash_profile
 # Get the aliases and functions
 if [ -f ~/.bashrc ]; then
 . ~/.bashrc
 fi
 # User specific environment and startup programs
PATH=$PATH:$HOME/bin:/apps/nginx/sbin:/usr/local/php/bin
 export PATH
 [root@Nginx ~]# source  .bash_profile

5.7 php的动态扩展模块(php的缓存模块)

安装memcache模块

[root@Nginx ~]# tar zxf memcache-8.2.tgz
 [root@Nginx ~]# cd memcache-8.2/
 [root@Nginx memcache-8.2]# yum install autoconf
 [root@Nginx memcache-8.2]# phpize
 [root@Nginx memcache-8.2]# ./configure && make && make install
 Installing shared extensions:     
/usr/local/php/lib/php/extensions/no-debug-non
zts-20230831/
 [root@Nginx memcache-8.2]# ls /usr/local/php/lib/php/extensions/no-debug-non-zts
20230831/
 memcache.so  opcache.so

复制测试文件到nginx发布目录中

[root@Nginx ~]# cd memcache-8.2/
 [root@Nginx memcache-8.2]# cp example.php  memcache.php  /data/php/
 [root@Nginx ~]# vim /data/php/memcache.php
 define('ADMIN_USERNAME','admin');   
// Admin Username
 define('ADMIN_PASSWORD','lee');   
src
 // 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

配置php加载memcache模块

[root@Nginx ~]# vim /usr/local/php/etc/php.ini
 ;extension=zip
 extension=memcache
 ;zend_extension=opcache
 [root@Nginx ~]# systemctl reload  php-fpm
 [root@Nginx no-debug-non-zts-20230831]# php -m | grep mem
 memcache

部署memcached

[root@Nginx ~]# cat /etc/sysconfig/memcached
 PORT="11211"
 USER="memcached"
 MAXCONN="1024"
 CACHESIZE="64"
 OPTIONS="-l 127.0.0.1,::1"

性能对比

[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

5.8 php高速缓存

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

[root@Nginx ~]# rm -fr /apps/nginx/
[root@Nginx ~]# tar zxf srcache-nginx-module-0.33.tar.gz
 [root@Nginx ~]# tar zxf memc-nginx-module-0.20.tar.gz
 [root@Nginx ~]# cd nginx-1.26.1/
 [root@Nginx 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@Nginx nginx-1.26.1]# make && make install
 [root@Nginx ~]# vim /apps/nginx/conf.d/php.conf
 upstream memcache {
 server 127.0.0.1:11211;
 keepalive 512;
 }
 server {
 listen 80;
 server_name php.timinglee.org;
 root /data/php;
 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 ~]# systemctl start nginx.service

测试结果:

[root@apache20 ~]# ab -n500 -c10 http://php.timinglee.org/index.php
 Concurrency Level:      10
 Time taken for tests:   0.255 seconds
 Complete requests:      500
 Failed requests:        0
相关推荐
‍理我1 小时前
Linux系统编程(基础指令)上
linux·服务器
如意机反光镜裸1 小时前
CentOS7搭建Hadoop3集群教程
运维
周湘zx1 小时前
k8s中的存储
linux·运维·云原生·容器·kubernetes
Linux猿1 小时前
828华为云征文 | 云服务器Flexus X实例:one-api 部署,支持众多大模型
服务器·大模型·llm·华为云·flexus云服务器x实例·华为云服务器·one-api
[听得时光枕水眠]2 小时前
【Docker】Docker上安装MySql8和Redis
运维·docker·容器
AI原吾2 小时前
解锁自动化新境界:KeymouseGo,让键盘和鼠标动起来!
运维·python·自动化·计算机外设·keymousego
_平凡之路_2 小时前
解决ubuntu22.04 gnome-terminal 无法启动的问题
linux·运维·python
凯子坚持 c2 小时前
0基础带你入门Linux之使用
linux·运维·服务器
hgdlip2 小时前
电脑ip会因为换了网络改变吗
服务器·网络·tcp/ip·电脑
EterNity_TiMe_2 小时前
【Linux基础IO】深入Linux文件描述符与重定向:解锁高效IO操作的秘密
linux·运维·服务器·学习·性能优化·学习方法