Nginx之正向代理ngx_http_proxy_connect_module编译和配置
ngx_http_proxy_connect_module 是一个转发代理模块,旨在处理 HTTP CONNECT 请求。此方法主要用于通过代理服务器传输 SSL 请求,从而实现客户端和远程服务器之间的安全通信。
主要特点
- CONNECT 方法支持:允许通过代理对 HTTPS 流量进行隧道传输。
- 端口控制:可配置为允许特定端口或范围进行代理。
- 超时管理:提供设置连接和数据超时的指令。
- 自定义响应:支持对 CONNECT 请求的自定义响应。
- 兼容性:适用于各种版本的 Nginx、OpenResty 和 Tengine。
安装步骤
1)下载ngx_http_proxy_connect_module模块
访问github官网下载对应版本 Release v0.0.7 · chobits/ngx_http_proxy_connect_module

tar zxvf ngx_http_proxy_connect_module.tar.gz
2)把ngx_http_proxy_connect_module模块编译进Nginx,新增模块参数,已安装模块也需要添加,不然就只有ngx_http_proxy_connect_module模块了
–add-module=/opt/tools/nginx/ngx_http_proxy_connect_module
# 加载ngx_http_proxy_connect_module补丁,选中对应的nginx版本
cd nginx/
patch -p1 < /path/to/ngx_http_proxy_connect_module/patch/proxy_connect.patch

./configure \
--sbin-path=/usr/local/nginx/nginx \
--conf-path=/usr/local/nginx/nginx.conf \
--pid-path=/usr/local/nginx/nginx.pid \
--user=nginx \
--group=nginx \
--with-compat \
--with-file-aio \
--with-threads \
--with-http_addition_module \
--with-http_auth_request_module \
--with-http_dav_module \
--with-http_flv_module \
--with-http_gunzip_module \
--with-http_gzip_static_module \
--with-http_mp4_module \
--with-debug \
--with-http_random_index_module \
--with-http_realip_module \
--with-http_secure_link_module \
--with-http_slice_module \
--with-pcre-jit \
--with-http_ssl_module \
--with-http_stub_status_module \
--with-http_sub_module \
--with-http_v2_module \
--with-http_v3_module \
--with-mail \
--with-mail_ssl_module \
--with-stream \
--with-stream_realip_module \
--with-stream_ssl_module \
--with-stream_ssl_preread_module \
--with-pcre=/opt/tools/nginx/pcre2-10.45 \
--with-zlib=/opt/tools/nginx/zlib-1.3.1 \
--add-module=/opt/tools/nginx/ngx_http_proxy_connect_module
make && make install
检查ngx_http_proxy_connect_module模块是否正常编译到nginx
nginx -v

3)测试nginx 正向代理
#正向代理转发http请求
server {
resolver 8.8.8.8 114.114.114.114;
listen 3128;
server_name localhost;
#正向代理转发http请求
location / {
proxy_pass http://$host$request_uri;
proxy_set_header HOST $host;
proxy_buffers 256 4k;
proxy_max_temp_file_size 0k;
proxy_connect_timeout 600;
proxy_send_timeout 600;
proxy_read_timeout 600;
proxy_next_upstream error timeout invalid_header http_502;
}
}
#正向代理转发https请求
server {
listen 3129;
server_name localhost;
resolver 114.114.114.114 8.8.8.8;
resolver_timeout 10s;
proxy_connect;
proxy_connect_allow 443 563;
proxy_connect_connect_timeout 600;
proxy_connect_read_timeout 600;
proxy_connect_send_timeout 600;
location / {
proxy_pass http://$host;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_http_version 1.1;
proxy_set_header Connection "";
# 允许 CONNECT 请求
if ($request_method = CONNECT) {
proxy_pass http://$host:443;
}
}
}
nginx -s reload
配置本地代理服务器

浏览器打开百度查看是否已经走代理服务器

检测nginx日志,是否有baidu的连接建立信息
