WEB服务与NGINX(20)- nginx 实现HTTP反向代理功能



1. nginx实现反向代理功能

1.1 nginx代理功能概述

代理分为正向代理和反向代理两种:

  • 正向代理

    正向代理一般指的是在客户端侧代替客户端向服务器发送请求,主要使用的场景为:

    • **上网(FQ)
    • 客户端提速(游戏加速器)
    • 客户端缓存,由代理服务器提供缓存功能,客户端请求时如果代理有缓存,则直接返回给客户端。
    • 客户端管控,一般由防火墙充当代理服务器,对客户端上网进行管控

    正向代理示意图如下:

image

  • 反向代理

    指的是代理外部用户的请求到内部指定的WEB服务器,并将数据返回给客户端的一种方式。主要使用的场景为:

    • 路由功能:根据用户请求的URL调度到不同的功能的服务器进行处理
    • 负载均衡
    • 动静分离:将客户端请求的动态资源和静态资源调度至不同的服务器进行处理
    • 数据缓存:将后端服务器返回的数据缓存在代理服务器上,加速用户获取资源

    反向代理的示意图如下:

image

nginx作为反向代理服务器主要使用下面的模块完成不同的功能:

  • ngx_http_proxy_module:

    将客户端的请求以http协议转发至指定服务器进行处理。

  • ngx_stream_proxy_module:

    将客户端的请求以tcp协议转发至指定服务器处理。

  • ngx_http_fastcgi_module:

    将客户端对php的请求以fastcgi协议转发至指定服务器助理。

  • ngx_http_uwsgi_module:

    将客户端对Python的请求以uwsgi协议转发至指定服务器处理。

1.2 NGINX实现HTTP反向代理

使用nginx做代理服务器不需要开启ip_forword转发,后端服务器接收到的请求报文ip为代理服务器Ip。

此场景的环境如下:

  • 客户端:192.16820.17
  • NGINX代理服务器:192.168.20.20
  • WEB服务器:使用apache充当,192.168.20.21

image

1.2.1 HTTP反向代理基本功能

1.2.1.1 反向代理配置参数

以下指令来自于ngx_http_proxy_module模块。

  • proxy_pass URL;

    支持环境:location, if in location, limit_except

    用来设置将客户端请求转发给的后端服务器的主机,可以是主机名、IP地址:端口的方式,也可以代理到预先设置的主机群组,需要模块ngx_http_upstream_module支持。

    注意:使用proxy_pass指令时,反代的地址最后有没有/的意义是不同的,请看下面的示例:

    #http://192.168.20.21:8080最后没有/表示:客户端端最终访问的是后端服务器的http://192.168.20.21:8080/test/index.html页面
    location /test {
        proxy_pass http://192.168.20.21:8080;
    }
    
    #http://192.168.20.21:80最后有/表示:客户端端最终访问的是后端服务器的http://192.168.20.21:80/index.html页面
    location /test {
        proxy_pass http://192.168.20.21:80/;
    }
    
  • proxy_set_header field value;

    支持环境:http, server, location

    可以更改或添加客户端的请求头部信息内容并转发至后端服务器,比如在后端服务器想要获取客户端的真实IP的时候,就要更改每一个报文的头部。即添加HOST到报文头部,如果客户端为NAT上网那么其值为客户端的公网IP地址。

    #用于向后端服务器传递客户端请求的HOST值,即服务器域名
    proxy_set_header Host $http_host;
    
    #将$remote_addr的值放入变量X-Real-IP中传递给后端服务器。
    proxy_set_header X-Real-IP  $remote_addr;
    
    #添加HOST到报文头部,用于在后端服务器日志中记录客户端真实IP地址
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    
  • proxy_hide_header field;

    支持环境:http, server, location

    用于nginx作为反向代理的时候,在返回给客户端http响应的时候,隐藏后端服务器特定的响应首部。

  • proxy_pass_hrader field;

    默认nginx在给客户的的响应报文中不传递后端服务器的首部字段Date, Server, XPad,X-Accel等,如果需要向客户端传递,使用proxy_pass_header 指令指定需要传递的字段。

  • proxy_pass_request_body

    是否向后端服务器发送HTTP包体部分,可以设置在http / server或location块,默认即为开启。

  • proxy_pass_request_headers

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

  • proxy_connect_timeout

    支持环境:http, server, location

    配置nginx服务器与后端服务器尝试建立连接的超时时间,默认为60秒。超时会给客户端返回502错误。

  • proxy_send_timeout

    支持环境:http, server, location

    将请求发送给后端服务器的超时时长,即向后端服务器发送write请求的超时时间;默认为60s。

  • proxy_read_timeout

    支持环境:http, server, location

    等待后端服务器发送响应报文的超时时长,即向后端服务器发起read请求的超时时间,默认为60s。

  • proxy_http_version 1.0|1.1

    用于设置nginx提供代理服务向后端服务器请求时使用的HTTP协议的版本,若需要使用长连接,建议修改为1.1版本。

  • proxy_ignore_client_abort

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

  • proxy_headers_hash_bucket_size

    当配置了 proxy_hide_header和proxy_set_header的时候,用于设置nginx保存HTTP报文头的hash表的上限。

  • proxy_headers_hash_max_size

    设置proxy_headers_hash_bucket_size的最大可用空间,设置服务器名称的hash表上限大小。

1.2.1.2 apache部署
#1.安装apache软件:
[root@apache01 ~]# yum install httpd -y
[root@apache01 ~]# rpm -q httpd
httpd-2.4.6-93.el7.centos.x86_64

#2.apache新增配置文件:
[root@apache01 ~]# cat /etc/httpd/conf.d/vhost.conf 
<VirtualHost 192.168.20.21:80>
	ServerName apache.xuzhichao.com
	DocumentRoot "/data/apache/xuzhichao"
	CustomLog "logs/apache.xuzhichao.log" combined
	<Directory "/data/apache/xuzhichao">
		options none
		allowoverride none
		Require all granted
	</Directory>	
</VirtualHost>

#3.启动httpd服务
[root@apache01 ~]# systemctl start httpd.service
[root@apache01 ~]# systemctl enable httpd.service

#4.新建相关工作目录
[root@apache01 ~]# mkdir /data/apache/xuzhichao -p
[root@apache01 ~]# chown apache:apache -R /data/apache/
[root@apache01 ~]# echo "<h1>apache.xuzhichao.com</h1>" > /data/apache/xuzhichao/index.html
[root@apache01 ~]# mkdir /data/apache/xuzhichao/www
[root@apache01 ~]# echo "<h1>apache.xuzhichao.com</h1>\n <h2>www dir</h2>" > /data/apache/xuzhichao/www/index.html

#5.客户端访问测试
[root@nginx01 ~]# curl http://192.168.20.21/
<h1>apache.xuzhichao.com</h1>
[root@nginx01 ~]# curl http://192.168.20.21/www/
<h1>apache.xuzhichao.com</h1>\n <h2>www dir</h2>
1.2.1.3 nginx反向代理配置
#示例一:
#1.nginx的配置文件如下:
[root@nginx01 ~]# cat /etc/nginx/conf.d/proxy_pass.conf 
server {
	listen 80;
	server_name proxy.xuzhichao.com;
	access_log /var/log/nginx/access.proxy.xuzhichao.log;

	location / {
		root /data/nginx/html/proxy_xuzhichao;
		index index.html index.php;
	}
	
	location /www {
		proxy_pass http://192.168.20.21:80;   <==没有以/结尾
		#proxy_pass http://192.168.20.21:80/;
	}
}

#2.新建nginx工作目录
[root@nginx01 ~]# mkdir /data/nginx/html/proxy_xuzhichao
[root@nginx01 ~]# echo "proxy.xuzhichao.com" > /data/nginx/html/proxy_xuzhichao/index.html

#3.重启nginx服务
[root@nginx01 ~]# systemctl reload nginx.service

#4.客户端测试
[root@xuzhichao ~]# curl http://proxy.xuzhichao.com
proxy.xuzhichao.com
[root@xuzhichao ~]# curl http://proxy.xuzhichao.com/www/
<h1>apache.xuzhichao.com</h1>\n <h2>www dir</h2>


#示例二:
#若把nginx的配置文件变为:
[root@nginx01 ~]# cat /etc/nginx/conf.d/proxy_pass.conf 
server {
	listen 80;
	server_name proxy.xuzhichao.com;
	access_log /var/log/nginx/access.proxy.xuzhichao.log;

	location / {
		root /data/nginx/html/proxy_xuzhichao;
		index index.html index.php;
	}
	
	location /www {
		#proxy_pass http://192.168.20.21:80;   
		proxy_pass http://192.168.20.21:80/;   <==以/结尾
	}
}

#2.重启nginx服务
[root@nginx01 ~]# systemctl reload nginx.service

#3.客户端测试
[root@xuzhichao ~]# curl http://proxy.xuzhichao.com
proxy.xuzhichao.com
[root@xuzhichao ~]# curl http://proxy.xuzhichao.com/www/
<h1>apache.xuzhichao.com</h1>


#查看apache服务器上的访问日志:
#可以看到记录的客户端的IP地址都是nginx服务器的地址,不是真实的客户端地址
[root@apache01 ~]# tail /var/log/httpd/apache.xuzhichao.log 
192.168.20.20 - - [24/Jun/2021:00:05:19 +0800] "GET / HTTP/1.1" 200 30 "-" "curl/7.29.0"
192.168.20.20 - - [24/Jun/2021:16:02:58 +0800] "GET / HTTP/1.1" 200 30 "-" "curl/7.29.0"
192.168.20.20 - - [24/Jun/2021:16:05:02 +0800] "GET /www/ HTTP/1.1" 200 49 "-" "curl/7.29.0"
192.168.20.20 - - [24/Jun/2021:16:18:19 +0800] "GET /www/ HTTP/1.0" 200 49 "-" "curl/7.29.0"
192.168.20.20 - - [24/Jun/2021:16:19:58 +0800] "GET // HTTP/1.0" 200 30 "-" "curl/7.29.0"
1.2.1.4 后端服务器显示客户端真实IP

在上一节中apache服务器的访问日志无法记录客户端真实IP,在日志分析时存在问题,可以使用如下方式让后端服务器记录客户端真实IP。

方法一:使用$remote_addr变量方式:

#1.nginx的配置文件如下:
[root@nginx01 ~]# cat /etc/nginx/conf.d/proxy_pass.conf 
server {
	listen 80;
	server_name proxy.xuzhichao.com;
	access_log /var/log/nginx/access.proxy.xuzhichao.log;

	location / {
		root /data/nginx/html/proxy_xuzhichao;
		index index.html index.php;
	}
	
	location /www {
		#proxy_pass http://192.168.20.21:80;
		proxy_pass http://192.168.20.21:80/;
		proxy_http_version 1.1;
		proxy_connect_timeout 30;
		proxy_send_timeout 60;
		proxy_read_timeout 60;

		proxy_set_header X-Real-IP $remote_addr;
	}
}

#2.重启nginx服务:
[root@nginx01 ~]# systemctl reload nginx.service

#3.apache服务器修改访问日志格式:
[root@apache01 ~]# cat /etc/httpd/conf.d/vhost.conf 
<VirtualHost 192.168.20.21:80>
	ServerName apache.xuzhichao.com
	DocumentRoot "/data/apache/xuzhichao"
	LogFormat "%{X-Real-IP}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined1
	#CustomLog "logs/apache.xuzhichao.log" combined
	CustomLog "logs/apache.xuzhichao.log" combined1
	<Directory "/data/apache/xuzhichao">
		options none
		allowoverride none
		Require all granted
	</Directory>	
</VirtualHost>


#4.重启httpd服务:
[root@apache01 ~]# systemctl reload httpd.service

#5.客户端访问,在apache上查看日志,可以看到客户端访问的真实IP
[root@xuzhichao ~]# curl http://proxy.xuzhichao.com/www/
<h1>apache.xuzhichao.com</h1>

[root@apache01 ~]# tail -f /var/log/httpd/apache.xuzhichao.log  
192.168.20.17 - - [24/Jun/2021:22:20:23 +0800] "GET // HTTP/1.1" 200 30 "-" "curl/7.29.0"

方法二:也可以使用$proxy_add_x_forwarded_for变量的方式:

#1.nginx的配置文件如下:
[root@nginx01 ~]# cat /etc/nginx/conf.d/proxy_pass.conf 
server {
	listen 80;
	server_name proxy.xuzhichao.com;
	access_log /var/log/nginx/access.proxy.xuzhichao.log;

	location / {
		root /data/nginx/html/proxy_xuzhichao;
		index index.html index.php;
	}
	
	location /www {
		#proxy_pass http://192.168.20.21:80;
		proxy_pass http://192.168.20.21:80/;
		proxy_http_version 1.1;
		proxy_connect_timeout 30;
		proxy_send_timeout 60;
		proxy_read_timeout 60;

		proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
	}
}

#2.重启nginx服务:
[root@nginx01 ~]# systemctl reload nginx.service

#3.apache服务器修改访问日志格式:
[root@apache01 ~]# cat /etc/httpd/conf.d/vhost.conf 
<VirtualHost 192.168.20.21:80>
	ServerName apache.xuzhichao.com
	DocumentRoot "/data/apache/xuzhichao"
	LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined1
	#CustomLog "logs/apache.xuzhichao.log" combined
	CustomLog "logs/apache.xuzhichao.log" combined1
	<Directory "/data/apache/xuzhichao">
		options none
		allowoverride none
		Require all granted
	</Directory>	
</VirtualHost>


#4.重启httpd服务:
[root@apache01 ~]# systemctl reload httpd.service

#5.客户端访问,在apache上查看日志,可以看到客户端访问的真实IP
[root@xuzhichao ~]# curl http://proxy.xuzhichao.com/www/
<h1>apache.xuzhichao.com</h1>

[root@apache01 ~]# tail -f /var/log/httpd/apache.xuzhichao.log  
192.168.20.17 - - [24/Jun/2021:22:31:17 +0800] "GET // HTTP/1.1" 200 30 "-" "curl/7.29.0"
1.2.1.5 nginx反代实现虚拟主机

在代理服务器上配置策略,将不同的请求发送到不同的虚拟主机上,默认情况代理服务器转发用户请求时,只会保留下目标IP地址,后端服务器就会认为访问的是IP地址,返回默认地址;

需要在代理服务器上增加新的头部信息让后端服务器识别FQDN,使用系统内建变量$host,可以在每个虚拟机中设置,也可以在http语句块中统一设置。

场景:在后端apache服务器上设置两个虚拟主机apache.xuzhichao.com和apache.xuzhichao.net,为客户端提供不同的服务。

#1.nginx的配置文件如下:
[root@nginx01 ~]# cat /etc/nginx/conf.d/proxy_pass.conf 
server {
	listen 80;
	server_name apache.xuzhichao.com;
	access_log /var/log/nginx/access.proxy.xuzhichao.log;
	
	location /www {
		proxy_pass http://192.168.20.21:80/;
		proxy_http_version 1.1;
		proxy_connect_timeout 30;
		proxy_send_timeout 60;
		proxy_read_timeout 60;

		proxy_set_header X-Real-IP $remote_addr;
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
		proxy_set_header host $host;    <==把客户端请求的$host赋值给host变量传递给后端虚拟主机
	}
}

server {
	listen 80;
	server_name apache.xuzhichao.net;
	access_log /var/log/nginx/access.proxy.xuzhichao.log;

	location /www {
		proxy_pass http://192.168.20.21:80/;
		proxy_http_version 1.1;
		proxy_connect_timeout 30;
		proxy_send_timeout 60;
		proxy_read_timeout 60;

		proxy_set_header X-Real-IP $remote_addr;
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
		proxy_set_header host $host;  <==把客户端请求的$host赋值给host变量传递给后端虚拟主机
	}
}

#2.重启ngxin服务:
[root@nginx01 ~]# systemctl reload nginx.service

#3.httpd的配置文件如下:
[root@apache01 ~]# vim /etc/httpd/conf.d/vhost.conf
<VirtualHost 192.168.20.21:80>
        ServerName apache.xuzhichao.com
        DocumentRoot "/data/apache/xuzhichao"
        #LogFormat "%{X-Real-IP}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined1
        LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined1
        #CustomLog "logs/apache.xuzhichao.log" combined
        CustomLog "logs/apache.xuzhichao.log" combined1
        <Directory "/data/apache/xuzhichao">
                options none
                allowoverride none
                Require all granted
        </Directory>
</VirtualHost>


<VirtualHost 192.168.20.21:80>
        ServerName apache.xuzhichao.net
        DocumentRoot "/data/apache/xuzhichao.net"
        LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined1
        CustomLog "logs/apache.xuzhichao.net.log" combined1
        <Directory "/data/apache/xuzhichao.net">                                                                                                                                                                                    
                options none
                allowoverride none
                Require all granted
        </Directory>
</VirtualHost>

#4.apache服务器上新建虚拟主机的工作目录
[root@apache01 ~]# mkdir /data/apache/xuzhichao.net
[root@apache01 ~]# echo "<h1>apache.xuzhichao.net</h1>" > /data/apache/xuzhichao.net/index.html

#5.重启apache服务
[root@apache01 ~]# systemctl reload httpd.service

#6.客户端配置/etc/hosts文件,访问测试:
root@xuzhichao ~]# cat /etc/hosts
192.168.20.20   www.nginx01.com  www.nginx02.com www.xuzhichao.com www.xuzhichao.net www.xuzhichao.com.cn www.xuzhichao.com.us proxy.xuzhichao.com apache.xuzhichao.com apache.xuzhichao.net

[root@xuzhichao ~]# curl http://apache.xuzhichao.net/www/
<h1>apache.xuzhichao.net</h1>

[root@xuzhichao ~]# curl http://apache.xuzhichao.com/www/
<h1>apache.xuzhichao.com</h1>
1.2.1.6 nginx反代实现隐藏后端服务器响应头部

nginx作为反向代理的时候,在返回给客户端http响应的时候,隐藏后端服务器特定的响应首部,使用proxy_hide_header field指令实现。

场景:隐藏后端服务器的ETag字段。

#依然使用上面的环境,没有变化的不再单独说明。
#1.nginx的配置文件如下:
[root@nginx01 ~]# cat /etc/nginx/conf.d/proxy_pass.conf 
server {
	listen 80;
	server_name apache.xuzhichao.com;
	access_log /var/log/nginx/access.proxy.xuzhichao.log;
	
	location /www {
		proxy_pass http://192.168.20.21:80/;
		proxy_http_version 1.1;
		proxy_connect_timeout 30;
		proxy_send_timeout 60;
		proxy_read_timeout 60;

		proxy_set_header X-Real-IP $remote_addr;
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
		proxy_set_header host $host;
		proxy_hide_header ETag;    <==隐藏后端服务器响应报文头部的ETag字段信息。
	}
}

server {
	listen 80;
	server_name apache.xuzhichao.net;
	access_log /var/log/nginx/access.proxy.xuzhichao.log;

	location /www {
		proxy_pass http://192.168.20.21:80/;
		proxy_http_version 1.1;
		proxy_connect_timeout 30;
		proxy_send_timeout 60;
		proxy_read_timeout 60;

		proxy_set_header X-Real-IP $remote_addr;
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
		proxy_set_header host $host;
	}
}

#2.重启ngxin服务:
[root@nginx01 ~]# systemctl reload nginx.service

#3.客户端访问测试:
[root@xuzhichao ~]# curl -i http://apache.xuzhichao.net/www/
HTTP/1.1 200 OK
Server: nginx
Date: Thu, 24 Jun 2021 15:07:28 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 30
Connection: keep-alive
Last-Modified: Thu, 24 Jun 2021 14:40:16 GMT
ETag: "1e-5c584006604d3"   <==访问这个虚拟主机有ETag信息
Accept-Ranges: bytes

<h1>apache.xuzhichao.net</h1>

#访问这个虚拟主机客户端没有收到ETag字段信息
[root@xuzhichao ~]# curl -i http://apache.xuzhichao.com/www/
HTTP/1.1 200 OK
Server: nginx
Date: Thu, 24 Jun 2021 15:08:01 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 30
Connection: keep-alive
Last-Modified: Wed, 23 Jun 2021 16:04:28 GMT
Accept-Ranges: bytes

<h1>apache.xuzhichao.com</h1>

1.2.2 NGINX反向代理的缓存功能

1.2.2.1 缓存功能配置参数

以下指令来自于ngx_http_proxy_module模块。

  • proxy_cache_path

    支持环境:http

    定义可用于proxy功能的缓存;nginx接受到被代理服务器的数据后,通过proxybuffer机制将数据传递给客户端,通过proxycache将数据缓存到本地硬盘。

    而open_file_cache则为nginx作为web服务器时对本地文件元数据的缓存。

    配置语法:

    proxy_cache_path  path  [levels=levels] [use_temp_path=on|off] keys_zone=name:size 
    				[inactive=time] [max_size=size] [manager_files=number] 
    				[manager_sleep=time] [manager_threshold=time] [loader_files=number] 
    				[loader_sleep=time] [loader_threshold=time] [purger=on|off] 
    				[purger_files=number] [purger_sleep=time] [purger_threshold=time];
    

    参数说明:

    • path:定义缓存文件在磁盘的保存路径,该文件会自动创建;
    • [levels=levels]:levels=1:2:2,定义缓存目录结构层次。缓存数据经过哈希运算,取多少级作为目录名,1:2:2可以生成2^4*2^8*2^8=1048576个目录;
    • keys_zone=name:size:表示被调用时所使用的名字,同时设定缓存占用的内存大小 (将用户请求的URI做哈希运算作为key放在内存中,对应的请求数据作为value放在磁盘中);
    • inactive=10m: 指定缓存有效时间,若超出该时间的缓存文件会被删除;
    • max_size=1g:最大磁盘占用空间,磁盘存入文件内容的缓存空间最大值;
  • proxy_cache zonename | off

    支持环境:http, server, location

    指明调用的缓存名称,或关闭缓存机制,默认关闭缓存。

  • proxy_cache_key

    支持环境:http, server, location

    设置nginx服务器在内存中为缓存数据建立索引时使用的关键字,即key包含的信息。

    默认值:proxy_cache_key $scheme​$proxy_host$request_uri;

  • proxy_cache_valid

    支持环境:http, server, location

    配置格式:proxy_cache_valid [code …] time;

    定义对特定响应码的响应内容的缓存时长。

    例如,为代码200和302的响应设置10分钟的缓存,为代码404的响应设置1分钟的缓存:

    proxy_cache_valid 200 302 10m;

    proxy_cache_valid 404 1m;

  • proxy_cache_use_stale

    支持环境:http, server, location

    配置格式

    proxy_cache_use_stale error | timeout | invalid_header | updating | http_500 | http_502 | http_503 | http_504 | http_403 | http_404 | off ...

    默认值

    proxy_cache_use_stale off;

    在被代理的后端服务器出现哪种情况下,可直接使用过期的缓存响应客户端。

  • proxy_cache_methods

    支持环境:http, server, location

    配置语法

    proxy_cache_methods GET | HEAD | POST ...;

    默认值

    proxy_cache_methods GET HEAD;

    对哪些客户端请求方法对应的响应进行缓存,GET和HEAD方法总是被缓存。

1.2.2.2 缓存场景示例

首先在没有配置缓存的情况下做nginx做压测,测试其性能。配置文件使用前一节的配置文件。

#1.客户端安装压测工具ab
[root@xuzhichao ~]# yum install http-tools -y

#2.对服务器进行压力测试
#一般进行压测时需要测试多次,然后去掉其中的最大和最小值,取平均值作为压测值。
#对服务器共发送100000次请求,每次并发1000个。
[root@xuzhichao ~]# ab -n 100000 -c 1000 http://proxy.xuzhichao.com/www/
This is ApacheBench, Version 2.3 <$Revision: 1430300 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking proxy.xuzhichao.com (be patient)
Completed 10000 requests
Completed 20000 requests
Completed 30000 requests
Completed 40000 requests
Completed 50000 requests
Completed 60000 requests
Completed 70000 requests
Completed 80000 requests
Completed 90000 requests
Completed 100000 requests
Finished 100000 requests


Server Software:        nginx
Server Hostname:        proxy.xuzhichao.com
Server Port:            80

Document Path:          /www/
Document Length:        30 bytes

Concurrency Level:      1000
Time taken for tests:   69.420 seconds
Complete requests:      100000
Failed requests:        5277
   (Connect: 0, Receive: 0, Length: 5277, Exceptions: 0)
Write errors:           0
Non-2xx responses:      5277
Total transferred:      27664987 bytes
HTML transferred:       3736020 bytes
Requests per second:    1440.50 [#/sec] (mean)    <==每秒完成的请求数,以此值作为参照进行对比;
Time per request:       694.201 [ms] (mean)
Time per request:       0.694 [ms] (mean, across all concurrent requests)
Transfer rate:          389.18 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    5  61.3      0    1006
Processing:     0  481 2942.1     65   54449
Waiting:        0  480 2942.1     65   54449
Total:          0  485 2948.5     66   54497

Percentage of the requests served within a certain time (ms)
  50%     66
  66%     71
  75%     81
  80%    257
  90%   1063
  95%   1270
  98%   3215
  99%   7020
 100%  54497 (longest request)


#测试5次,5次的结果如下:
#第一次:
Requests per second:    1440.50 [#/sec] (mean) 
#第二次:
Requests per second:    1306.69 [#/sec] (mean)
#第三次:
Requests per second:    1558.03 [#/sec] (mean)
#第四次:
Requests per second:    1258.68 [#/sec] (mean)
#第五次:
Requests per second:    1415.28 [#/sec] (mean)
#去掉最大值和最小值,平均值为:
1387.49

在nginx配置缓存的情况下再进行压测比对。

#1.nginx的配置文件如下:
#在nginx主配置文件中增加代理缓存配置:
root@nginx01 ~]# vim /etc/nginx/nginx.conf
http {
    ......
    proxy_cache_path /data/nginx/proxy_cache levels=1:1:1 keys_zone=proxycache:256m inactive=10m max_size=1g;
}

#在nginx子配置文件中增加代理缓存配置:
server {
        listen 80;
        server_name proxy.xuzhichao.com;
        access_log /var/log/nginx/access.proxy.xuzhichao.log;

        location / {
                root /data/nginx/html/proxy_xuzhichao;
                index index.html index.php;
        }

        location /www {
                #proxy_pass http://192.168.20.21:80;
                proxy_pass http://192.168.20.21:80/;
                proxy_http_version 1.1;
                proxy_connect_timeout 30;
                proxy_send_timeout 60;
                proxy_read_timeout 60;

                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

                proxy_cache proxycache;
                proxy_cache_key $request_uri;
                proxy_cache_valid 200 302 301 1h;
                proxy_cache_valid any 5m;                                             
        }
}

#2.重启nginx服务:
[root@nginx01 ~]# systemctl reload nginx.service

#3.客户端进行压测:
[root@xuzhichao ~]# ab -n 100000 -c 1000 http://proxy.xuzhichao.com/www/
This is ApacheBench, Version 2.3 <$Revision: 1430300 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking proxy.xuzhichao.com (be patient)
Completed 10000 requests
Completed 20000 requests
Completed 30000 requests
Completed 40000 requests
Completed 50000 requests
Completed 60000 requests
Completed 70000 requests
Completed 80000 requests
Completed 90000 requests
Completed 100000 requests
Finished 100000 requests


Server Software:        nginx
Server Hostname:        proxy.xuzhichao.com
Server Port:            80

Document Path:          /www/
Document Length:        30 bytes

Concurrency Level:      1000
Time taken for tests:   20.026 seconds
Complete requests:      100000
Failed requests:        0
Write errors:           0
Total transferred:      27400000 bytes
HTML transferred:       3000000 bytes
Requests per second:    4993.53 [#/sec] (mean)
Time per request:       200.259 [ms] (mean)
Time per request:       0.200 [ms] (mean, across all concurrent requests)
Transfer rate:          1336.16 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        1  115 223.6     74    3101
Processing:    16   84  27.8     88     300
Waiting:        6   66  24.7     67     291
Total:         30  199 228.5    167    3192

Percentage of the requests served within a certain time (ms)
  50%    167
  66%    184
  75%    190
  80%    194
  90%    222
  95%    328
  98%   1152
  99%   1171
 100%   3192 (longest request)

#测试5次,5次的结果如下:
#第一次:
Requests per second:    4993.53 [#/sec] (mean) 
#第二次:
Requests per second:    5021.55 [#/sec] (mean)
#第三次:
Requests per second:    4985.95 [#/sec] (mean)
#第四次:
Requests per second:    4660.08 [#/sec] (mean)
#第五次:
Requests per second:    4688.35 [#/sec] (mean)
#去掉最大值和最小值,平均值为:
4889.19
比没有启用缓存提升了71.62% [(4889.19-1387.49)%4889.19*100] 的性能。

查看nginx缓存的内容如下:

#查看缓存生成的目录:
[root@nginx01 ~]# ll /data/nginx/proxy_cache/
total 0
drwx------ 3 nginx nginx 15 Jun 25 22:09 5

[root@nginx01 ~]# ll /data/nginx/proxy_cache/ -d
drwx------ 3 nginx root 15 Jun 25 22:09 /data/nginx/proxy_cache/

[root@nginx01 ~]# tree /data/nginx/proxy_cache/
/data/nginx/proxy_cache/
└── 5
    └── c
        └── 9
            └── 8b9f15be8cfeee67883bac9aa91899c5

3 directories, 1 file

#查看缓存的页面内容:
[root@nginx01 ~]# head -n 100 /data/nginx/proxy_cache/5/c/9/8b9f15be8cfeee67883bac9aa91899c5 
°򔠌[Ҡ 䔠P{J蚁`"1e-5c5710faa6ed2"
KEY: /www/            <==可以看到key是我们定义的$request_uri;
HTTP/1.1 200 OK
Date: Fri, 25 Jun 2021 14:09:36 GMT
Server: Apache/2.4.6 (CentOS)
Last-Modified: Wed, 23 Jun 2021 16:04:28 GMT
ETag: "1e-5c5710faa6ed2"
Accept-Ranges: bytes
Content-Length: 30
Connection: close
Content-Type: text/html; charset=UTF-8

<h1>apache.xuzhichao.com</h1>

1.2.3 NGINX反向代理——添加头部报文信息

nginx作为反向代理服务器时可以给客户端的响应报文添加自定义的首部,或修改指定首部的值。

该功能由ngx_http_headers_module模块提供,使用的指令如下:

  • add_header name value [always];

    支持环境:http, server, location, if in location

    添加一个指定的字段到响应头部中,当响应码为200, 201 (1.3.10), 204, 206, 301, 302, 303, 304, 307 (1.1.16, 1.0.13), or 308 (1.13.0),此添加头部为自定义项,字段名和值都由自己自定,值可以为变量;如果指定参数always,则不管响应码如何,都添加指定字段。

    例如:

    #为客户端的响应报文添加如下字段。
    add_header X-via $server_addr; (nginx服务器地址)
    add_header X-Cache $upstream_cache_status; ( nginx内部变量,用来显示缓存命中状态)
    add_header X-Accel $server_name;(请求的server_name)
    

使用示例如下:

#1.nginx的配置文件如下:
[root@nginx01 ~]# cat /etc/nginx/conf.d/proxy_pass.conf 
server {
	listen 80;
	server_name proxy.xuzhichao.com;
	access_log /var/log/nginx/access.proxy.xuzhichao.log;

	location /www {
		#proxy_pass http://192.168.20.21:80;
		proxy_pass http://192.168.20.21:80/;
		
		proxy_http_version 1.1;
		proxy_connect_timeout 30;
		proxy_send_timeout 60;
		proxy_read_timeout 60;

		proxy_set_header X-Real-IP $remote_addr;
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

		proxy_cache proxycache;
		proxy_cache_key $request_uri;
		proxy_cache_valid 200 302 301 1h;
		proxy_cache_valid any 5m;

		add_header X-via $server_addr;
		add_header X-cache $upstream_cache_status;
		add_header X-Accel $server_name;
	}
}

#2.重启nginx服务:
[root@nginx01 ~]# systemctl reload nginx.service 

#3.客户端访问测试:
[root@xuzhichao ~]# curl -i http://proxy.xuzhichao.com/www/
HTTP/1.1 200 OK
Server: nginx
Date: Sat, 26 Jun 2021 09:13:14 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 30
Connection: keep-alive
Last-Modified: Wed, 23 Jun 2021 16:04:28 GMT
ETag: "1e-5c5710faa6ed2"
X-via: 192.168.20.20   <==增加的头部信息
X-cache: MISS   <== 第一次访问未命中缓存
X-Accel: proxy.xuzhichao.com  <==增加的头部信息
Accept-Ranges: bytes

<h1>apache.xuzhichao.com</h1>

[root@xuzhichao ~]# curl -i http://proxy.xuzhichao.com/www/
HTTP/1.1 200 OK
Server: nginx
Date: Sat, 26 Jun 2021 09:13:17 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 30
Connection: keep-alive
Last-Modified: Wed, 23 Jun 2021 16:04:28 GMT
ETag: "1e-5c5710faa6ed2"
X-via: 192.168.20.20
X-cache: HIT    <== 第二次访问命中缓存
X-Accel: proxy.xuzhichao.com
Accept-Ranges: bytes

<h1>apache.xuzhichao.com</h1>
posted @ 2021-06-27 18:16  向往自由的独行者  阅读(682)  评论(0编辑  收藏  举报