# 正、反向代理和四层代理 ## 正向代理 ![](./11.png) 正向代理,客户端和代理服务器可以看成一个整体 ![](./12.png) ### 需求场景 Nginx正向代理使用场景并不多见。 需求场景1: 如果在机房中,只有一台机器可以联网,其他机器只有内网,内网的机器想使用yum安装软件包,在能联网的机器上配置一个正向代理即可。 ### 配置文件 说明: 以下配置文件为nginx官方提供,该方法只能实现针对http的网站的访问,如果是https就会有问题。要想实现https的正向代理,可以使用一个三方模块,后面介绍。 ```bash server { listen 80 default_server; resolver 119.29.29.29; location / { proxy_pass http://$host$request_uri; } } ``` 配置说明: - resolver 119.29.29.29; 指定DNS服务器地址,这个DNS服务器地址可以是本地的,也可以是公网的,这里使用的是公网的DNS服务器地址。国内通用的DNS 119.29.29.29为dnspod公司提供。 国际通用DNS 8.8.8.8或者8.8.4.4为google提供。 其他可以参考 http://dns.lisect.com/ - default_server; 之所以要设置为默认虚拟主机,是因为这样就不用设置server_name了,任何域名解析过来都可以正常访问。 - proxy_pass http://$host$request_uri; 将请求转发到http://$host$request_uri,$host表示请求的域名,$request_uri表示请求的URI。 该指令用来设置要代理的目标url,正向代理服务器设置就保持该固定值即可。 ```bash server { listen 80 default_server; resolver 119.29.29.29; location / { proxy_pass http://$host$request_uri; } } [root@lwz1 vhost]# !curl curl -x127.0.0.1:80 www.baidu.com -I HTTP/1.1 200 OK Server: nginx/1.23.1 Date: Tue, 19 Mar 2024 06:12:29 GMT Content-Type: text/html Content-Length: 277 Connection: keep-alive Accept-Ranges: bytes Cache-Control: private, no-cache, no-store, proxy-revalidate, no-transform Etag: "575e1f71-115" Last-Modified: Mon, 13 Jun 2016 02:50:25 GMT Pragma: no-cache ``` ### 正向代理支持https 下载三方模块ngx_http_proxy_connect_module github地址:https://github.com/chobits/ngx_http_proxy_connect_module (注意,不同的Nginx版本,还需要下载不同的patch包。) 下面的例子,以1.23.1为例 ```bash # 下载模块 cd /usr/local/src/ wget https://codeload.github.com/chobits/ngx_http_proxy_connect_module/zip/refs/heads/master mv master ngx_http_proxy_connect_module.zip unzip ngx_http_proxy_connect_module.zip # 使用patch工具打补丁,选择对应nginx版本的模块 cd ../nginx-1.23.1 yum install -y patch patch -p1 < ../ngx_http_proxy_connect_module-master/patch/proxy_connect_rewrite_102101.patch ./configure --prefix=/usr/local/nginx --add-module=/usr/local/src/echo-nginx-module --with-http_v2_module --add-module=../ngx_http_proxy_connect_module-master; make systemctl stop nginx; mv /usr/local/nginx/sbin/nginx{,.bak.2}; cp objs/nginx /usr/local/nginx/sbin/ systemctl start nginx ``` ```bash # 配置文件 server { listen 3128; # dns resolver used by forward proxying resolver 119.29.29.29; # forward proxy for CONNECT request proxy_connect; proxy_connect_allow 80 443 3000 9070 9074; proxy_connect_connect_timeout 10s; proxy_connect_read_timeout 10s; proxy_connect_send_timeout 10s; # forward proxy for non-CONNECT request location / { proxy_pass http://$host; proxy_set_header Host $host; } } ``` ```bash # 测试 [root@lwz1 vhost]# curl -x127.0.0.1:3128 https://www.baidu.com 百度一下,你就知道