Nginx 的反向代理功能

Nginx 的反向代理功能

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

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

ngx_http_proxy_module: 将客户端的请求以http协议转发至指定服务器进行处理。
ngx_stream_proxy_module:将客户端的请求以tcp协议转发至指定服务器处理。
ngx_http_fastcgi_module:将客户端对php的请求以fastcgi协议转发至指定服务器助理。
ngx_http_uwsgi_module:将客户端对Python的请求以uwsgi协议转发至指定服务器处理。

逻辑调用关系:
在这里插入图片描述

生产环境部署结构:

图片源于马哥教育教材
在这里插入图片描述

1 .实现http反向代理

要求:将用户对域 www.daming.net的请求转发值后端服务器处理,官方文档: https://nginx.org/en/docs/http/ngx_http_proxy_module.html,

环境准备:

192.168.66.7   # Nginx 代理服务器
192.168.66.17  # 后端web A,Apache部署
192.168.66.27  # 后端web B,Apache部署

访问逻辑图:

在这里插入图片描述

1.1:部署后端Apache服务器

[root@s3 ~]# yum install httpd -y
[root@s3 ~]# echo "web1 192.168.66.17" > /var/www/html/index.html
[root@s3 ~]# systemctl start httpd && systemctl enable httpd
[root@s4 ~]# yum install httpd -y
[root@s4 ~]# echo "web2 192.168.66.27" >> /var/www/html/index.html
[root@s4 ~]# systemctl start httpd && systemctl enable httpd
#访问测试
[root@s4 ~]# curl http://192.168.66.17
web1 192.168.66.17
[root@s3 ~]# curl http://192.168.66.27
web2 192.168.66.27

1.2 Nginx http 反向代理入门

参看官方文档:https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass

1.2.1 反向代理配置参数

proxy_pass;
#用来设置将客户端请求转发给的后端服务器的主机,可以是主机名、IP地址:端口的方式,也可以代理到预先设置的
主机群组,需要模块gx_http_upstream_module支持。
location /web {
 index index.html;
 proxy_pass http://192.168.66.17:80;
  #不带斜线将访问的/web,等于访问后端服务器 http://192.168.66.17:80/web/index.html,即后端服务器配置的站点根目录要有web目录才可以被访问,这是一个追加/web到后端服务器
http://servername:port/WEB/INDEX.HTML的操作
 proxy_pass http://192.168.66.17:80/;
  #带斜线,等于访问后端服务器的http://192.168.66.17:80/index.html 内容返回给客户端
}
#重启Nginx测试访问效果:
# curl -L http://www.daming.net/web/index.html
proxy_hide_header field;
#用于nginx作为反向代理的时候,在返回给客户端http响应的时候,隐藏后端服务版本相应头部的信息,可以设置在
http/server或location块,
location /web {
 index index.html;
 proxy_pass http://192.168.66.17:80/;
 proxy_hide_header ETag;
}
proxy_pass_header field;
#默认nginx在响应报文中不传递后端服务器的首部字段Date, Server, X-Pad, X-Accel等参数,如果要传递的
话则要使用 proxy_pass_header field声明将后端服务器返回的值传递给客户端。
proxy_pass_request_body on | off;
#是否向后端服务器发送HTTP包体部分,可以设置在http/server或location块,默认即为开启
proxy_pass_request_headers on | off;
#是否将客户端的请求头部转发给后端服务器,可以设置在http/server或location块,默认即为开启
proxy_set_header;
#可以更改或添加客户端的请求头部信息内容并转发至后端服务器,比如在后端服务器想要获取客户端的真实IP的时
候,就要更改每一个报文的头部,如下:
#proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-For  $remote_addr; 
#添加HOST到报文头部,如果客户端为NAT上网那么其值为客户端的共用的公网IP地址,常用于在日之中记录客户端的真实IP地址。
proxy_connect_timeout time;
#配置nginx服务器与后端服务器尝试建立连接的超时时间,默认为60秒,用法如下:
proxy_connect_timeout 60s;
#60s为自定义nginx与后端服务器建立连接的超时时间
proxy_read_time time;
#配置nginx服务器向后端服务器或服务器组发起read请求后,等待的超时时间,默认60s
proxy_send_time time;
#配置nginx项后端服务器或服务器组发起write请求后,等待的超时时间,默认60s
proxy_http_version 1.0;
#用于设置nginx提供代理服务的HTTP协议的版本,默认http 1.0
proxy_ignore_client_abort off;
#当客户端网络中断请求时,nginx服务器中断其对后端服务器的请求。即如果此项设置为on开启,则服务器会忽略客
户端中断并一直等着代理服务执行返回,如果设置为off,则客户端中断后Nginx也会中断客户端请求并立即记录499日
志,默认为off
proxy_headers_hash_bucket_size 128;
#当配置了 proxy_hide_header和proxy_set_header的时候,用于设置nginx保存HTTP报文头的hash表的上
限。
proxy_headers_hash_max_size 512;
#设置proxy_headers_hash_bucket_size的最大可用空间
server_namse_hash_bucket_size 512;
#server_name hash表申请空间大小
server_names_hash_max_szie  512;
#设置服务器名称hash表的上限大小

1.2.2 反向代理示例–单台web服务器

[root@s2 conf.d]# cat pc.conf
server {
	listen 80;
	server_name www.daming.net;

	location / {
	 proxy_pass http://192.168.66.17:80/;
	}
}
#重启Nginx 并访问测试

1.2.3 反向代理示例–指定location

server {
	listen 80;
	server_name www.daming.net;

	location / {
		index index.html index.php;
 root /data/nginx/html/pc;
 }
	location /web {
 #proxy_pass http://192.168.66.17:80/; #注意有后面的/,
 	proxy_pass http://192.168.66.27:80/;
	}
}
#后端web服务器必须要有相对于的访问URL
[root@s3 ~]# mkdir /var/www/html/web
[root@s3 ~]# echo "web1 page for apache" > /var/www/html/web/index.html
[root@s4 ~]# mkdir /var/www/html/web
[root@s4 ~]# echo "web2 page for apache" > /var/www/html/web/index.html

#重启Nginx并访问测试:
[root@s2 ~]# curl -L http://www.daming.net/
pc web
[root@s2 ~]# curl -L http://www.daming.net/web
web2 page for apache
#Apache的访问日志:
[root@s4 ~]# tail -f /var/log/httpd/access_log
192.168.66.7 - - [04/Mar/2019:18:52:00 +0800] "GET /web/ HTTP/1.1" 200 21 "-"
"curl/7.29.0"
192.168.66.7 - - [04/Mar/2019:18:52:00 +0800] "GET /web HTTP/1.0" 301 233 "-"
"curl/7.29.0"
192.168.66.7 - - [04/Mar/2019:18:52:00 +0800] "GET /web/ HTTP/1.1" 200 21 "-"
"curl/7.29.0"

1.2.4 反向代理示例–缓存功能

缓存功能默认关闭状态

proxy_cache zone | off; 默认off
#指明调用的缓存,或关闭缓存机制;Context:http, server, location

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

proxy_cache_valid [code ...] time;
#定义对特定响应码的响应内容的缓存时长,定义在http{...}中
示例:
	proxy_cache_valid 200 302 10m;
	proxy_cache_valid 404 1m;

proxy_cache_path; #查看官方文档最为准确
定义可用于proxy功能的缓存;Context:http
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];
**示例:在http配置定义缓存信息**
 proxy_cache_path /var/cache/nginx/proxy_cache #定义缓存保存路径,proxy_cache会自动创建
 levels=1:2:2 #定义缓存目录结构层次,1:2:2可以生成2^4x2^8x2^8=1048576个目录
 keys_zone=proxycache:20m #指内存中缓存的大小,主要用于存放key和metadata(如:使用次数) 
 inactive=120s; #缓存有效时间 
 max_size=1g; #最大磁盘占用空间,磁盘存入文件内容的缓存空间最大值

#调用缓存功能,需要定义在相应的配置段,如server{...};或者location等
   proxy_cache proxycache;
   proxy_cache_key $request_uri;
   proxy_cache_valid 200 302 301 10m; #指定的状态码返回的数据缓存多长时间
   proxy_cache_valid any 1m;

proxy_cache_use_stale error http_502 http_503;
#在被代理的后端服务器出现哪种情况下,可直接使用过期的缓存响应客户端,
proxy_cache_use_stale error | timeout | invalid_header | updating | http_500 | http_502
| http_503 | http_504 | http_403 | http_404 | off ; #默认是off

proxy_cache_methods GET | HEAD | POST ...;
#对哪些客户端请求方法对应的响应进行缓存,GET和HEAD方法总是被缓存

1.2.5:添加头部报文信息

nginx基于模块ngx_http_headers_module可以实现对头部报文添加指定的key与值

参考文档: https://nginx.org/en/docs/http/ngx_http_headers_module.html

Syntax: add_header name value [always];
Default: —
Context: http, server, location, if in location
#添加自定义首部,如下:
add_header name value [always];
add_header X-Via  $server_addr;
add_header X-Cache $upstream_cache_status;
add_header X-Accel $server_name;
#添加自定义响应信息的尾部, 1.13.2版后支持
add_trailer name value [always];
  • Nginx配置
location /web {
 proxy_pass http://192.168.66.17:80/;
 proxy_set_header clientip $remote_addr;
 proxy_cache proxycache;
 proxy_cache_key $request_uri;
 proxy_cache_valid 200 302 301 1h;
 proxy_cache_valid any 1m;
 add_header X-Via  $server_addr;
 add_header X-Cache $upstream_cache_status;
 add_header X-Accel $server_name;
}

验证头部信息:

[root@nginx ~]# curl -v 127.0.0.1/app1/
* About to connect() to 127.0.0.1 port 80 (#0)
*   Trying 127.0.0.1...
* Connected to 127.0.0.1 (127.0.0.1) port 80 (#0)
> GET /app1/ HTTP/1.1
> User-Agent: curl/7.29.0
> Host: 127.0.0.1
> Accept: */*
> 
< HTTP/1.1 200 OK
< Server: nginx/1.16.1
< Date: Tue, 07 Jan 2020 08:56:28 GMT
< Content-Type: text/html; charset=UTF-8
< Content-Length: 29
< Connection: keep-alive
< Last-Modified: Tue, 07 Jan 2020 07:05:23 GMT
< ETag: "1d-59b87665f5400"
< X-Via: 127.0.0.1
< X-Cache: MISS    #---->第一次访问没有缓存
< X-Accel: www.daming.net
< Accept-Ranges: bytes
< 
app1 web page by web1 server
* Connection #0 to host 127.0.0.1 left intact
[root@nginx ~]# tree /apps/nginx/proxycache/
/apps/nginx/proxycache/
└── b
    └── 27
        └── 73
            └── 45efea0da7a0718cc36ddeda8747327b

3 directories, 1 file
[root@nginx ~]# curl -v 127.0.0.1/app1/
* About to connect() to 127.0.0.1 port 80 (#0)
*   Trying 127.0.0.1...
* Connected to 127.0.0.1 (127.0.0.1) port 80 (#0)
> GET /app1/ HTTP/1.1
> User-Agent: curl/7.29.0
> Host: 127.0.0.1
> Accept: */*
> 
< HTTP/1.1 200 OK
< Server: nginx/1.16.1
< Date: Tue, 07 Jan 2020 08:57:04 GMT
< Content-Type: text/html; charset=UTF-8
< Content-Length: 29
< Connection: keep-alive
< Last-Modified: Tue, 07 Jan 2020 07:05:23 GMT
< ETag: "1d-59b87665f5400"
< X-Via: 127.0.0.1
< X-Cache: HIT  #第二次缓存命中
< X-Accel: www.daming.net
< Accept-Ranges: bytes
< 
app1 web page by web1 server
* Connection #0 to host 127.0.0.1 left intact

2. Nginx http 反向代理高级应用

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

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

2.1 http upstream配置参数

upstream name {
}
#自定义一组服务器,配置在http内
server address [parameters];
#配置一个后端web服务器,配置在upstream内,至少要有一个server服务器配置。
#server支持的parameters如下:
weight=number #设置权重,默认为1。
max_conns=number  #给当前server设置最大活动链接数,默认为0表示没有限制。
max_fails=number  #对后端服务器连续监测失败多少次就标记为不可用。
fail_timeout=time #对后端服务器的单次监测超时时间,默认为10秒。
backup  #设置为备份服务器,当所有服务器不可用时将重新启用次服务器。
down   #标记为down状态。
resolve #当server定义的是主机名的时候,当A记录发生变化会自动应用新IP而不用重启Nginx。
hash KEY consistent;
#基于指定key做hash计算,使用consistent参数,将使用ketama一致性hash算法,适用于后端是Cache服务器
(如varnish)时使用,consistent定义使用一致性hash运算,一致性hash基于取模运算。
hash $request_uri consistent; #基于用户请求的uri做hash
ip_hash;
#源地址hash调度方法,基于的客户端的remote_addr(源地址)做hash计算,以实现会话保持
least_conn;
#最少连接调度算法,优先将客户端请求调度到当前连接最少的后端服务器

2.1.1 反向代理示例–多台web服务器

upstream webserver {
 	#hash $request_uri consistent;
	 #ip_hash;
	 #least_conn;
	server 192.168.66.17:80 weight=1 fail_timeout=5s 			max_fails=3; #后端服务器状态监测
	server 192.168.66.27:80 weight=1 fail_timeout=5s max_fails=3;
	server  192.168.66.7:80 weight=1 fail_timeout=5s max_fails=3 backup;
}
server {
	listen 80;
	server_name www.daming.net;
	location / {
 		index index.html index.php;
 		root /data/nginx/html/pc;
 }
	location /web {
 		index index.html;
 		proxy_pass http://webserver/;
}
}
#重启Nginx 并访问测试

[root@s2 ~]# curl  http://www.daming.net/web
web1 192.168.66.17
[root@s2 ~]# curl http://www.daming.net/web
web2 192.168.66.27

关闭192.168.66.17和192.168.66.27,测试nginx backup服务器可用性

[root@s4 ~]# while true;do curl http://www.daming.net/web;sleep 1;done
# 测试轮询?

2.1.2 反向代理示例–客户端IP透传

[root@s2 conf.d]# cat pc.conf
upstream webserver {
 #hash $request_uri consistent; #consistent 一致性hash算法
 #server 192.168.7.103:80 weight=1 fail_timeout=5s max_fails=3;
	server 192.168.66.27:80 weight=1 fail_timeout=5s max_fails=3;
	server  192.168.66.7:80 weight=1 fail_timeout=5s max_fails=3 backup;
}
	server {
		listen 80;
		server_name www.daming.net;
		location / {
			 index index.html index.php;
			 root /data/nginx/html/pc;
 		}
		location /web {
			 index index.html;
 			 proxy_pass http://webserver/;
 			 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #添加客户端IP到报文头部
		}
}
#重启nginx
#后端web服务器配置
1、Apache:
[root@s4 ~]# vim /etc/httpd/conf/httpd.conf
LogFormat "%{X-Forwarded-For}i %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-
Agent}i\"" combined
#重启apache访问web界面并验证apache日志

2、Nginx:
[root@s1 conf.d]# cat /apps/nginx/conf/nginx.conf
"$http_x_forwarded_for"' #默认日志格式就有此配置
重启nginx访问web界面并验证日志格式
发布了39 篇原创文章 · 获赞 2 · 访问量 1025

猜你喜欢

转载自blog.csdn.net/weixin_45341507/article/details/103878893