Nginx 正向代理
需求
服务部署于k8s中,但有一部分服务需要访问第三方接口,对端需要对IP加白。k8s节点过多且ip可能发生变化,所有通过配置一台或两台服务器进行正向代理,使得部分服务可以通过代理地址使用少数且固定的公网IP进行白名单认证。
Nginx部署
yum install -y wget gcc gcc-c++ make pcre pcre-devel zlib zlib-devel openssl openssl-devel gd-devel patch
wget 'http://nginx.org/download/nginx-1.26.2.tar.gz'
tar -zxvf nginx-1.26.2.tar.gz
# 添加正向代理模块
wget https://github.com/chobits/ngx_http_proxy_connect_module/archive/refs/tags/v0.0.7.zip
unizp v0.0.7.zip
# 此处需要对应版本读取补丁,https://github.com/halo-dev/plugin-search-widget
cd nginx-1.26.2
patch -p1 < /usr/local/src/ngx_http_proxy_connect_module-0.0.7/patch/proxy_connect_rewrite_102101.patch
./configure --prefix=/usr/local/nginx --with-pcre --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_addition_module --with-http_sub_module --with-http_dav_module --with-http_flv_module --with-http_mp4_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_random_index_module --with-http_secure_link_module --with-http_stub_status_module --with-http_auth_request_module --with-http_image_filter_module --with-http_slice_module --with-mail --with-threads --with-file-aio --with-stream --with-mail_ssl_module --with-stream_ssl_module --add-module=/usr/local/src/ngx_http_proxy_connect_module-0.0.7
make && make install
cat > /etc/systemd/system/nginx.service << EOF
[Unit]
Description=The NGINX HTTP and reverse proxy server
After=syslog.target network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target
[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
ln -s /usr/local/nginx/sbin/nginx /usr/local/bin/nginx
systemctl enable --no wnginx
配置修改
# 修改nginx配置文件
server {
listen 8080;
server_name localhost;
resolver 8.8.8.8 ipv6=off;
proxy_connect;
proxy_connect_allow all;
proxy_connect_connect_timeout 10s;
proxy_connect_read_timeout 10s;
#proxy_coneect_send_timeout 10s;
location / {
proxy_pass $scheme://$http_host$request_uri;
proxy_set_header HOST $host;
proxy_ssl_server_name on;
}
}
# 重新加载nginx服务
nginx -t
nginx -s reload
访问测试
另找一台可以访问ngixn服务的服务器进行测试
curl --proxy 172.31.30.125:8080 http://ip.3322.net
此时将返回nginx服务器的公网IP
此时可在服务中配置使用此端点进行代理访问。
所有流量代理
在服务器环境变量中进行配置。服务器将所有符合的流量都进行正向代理
export HTTP_PROXY=http://172.31.30.125:8080
export HTTPS_PROXY=http://172.31.30.125:8080
# 处理内网流量,不走代理
export NO_PROXY="172.31.16.0/20,localhost,127.0.0.1"