使用nginx正向代理,实现内网服务器访问外网

84 阅读1分钟

ngx_http_proxy_connect_module

使用nginx插件ngx_http_proxy_connect_module ,它允许Nginx作为代理服务器处理CONNECT方法。CONNECT 方法通常用于建立到远程服务器的端到端的加密连接,通常在代理服务器后面的客户端需要通过代理服务器与目标服务器建立安全连接。

安装patch

#安装patch:
yum install patch -y

下载nginx并解压

cd /usr/local
wget https://nginx.org/download/nginx-1.24.0.tar.gz
tar -zxvf nginx-1.24.0.tar.gz

下载ngx_http_proxy_connect_module

cd nginx-1.24.0
git clone https://github.com/chobits/ngx_http_proxy_connect_module.git

根据对照表安装对应的版本

nginx versionenable REWRITE phasepatch
1.4.x ~ 1.12.xNOproxy_connect.patch
1.4.x ~ 1.12.xYESproxy_connect_rewrite.patch
1.13.x ~ 1.14.xNOproxy_connect_1014.patch
1.13.x ~ 1.14.xYESproxy_connect_rewrite_1014.patch
1.15.2YESproxy_connect_rewrite_1015.patch
1.15.4 ~ 1.16.xYESproxy_connect_rewrite_101504.patch
1.17.x ~ 1.18.xYESproxy_connect_rewrite_1018.patch
1.19.x ~ 1.21.0YESproxy_connect_rewrite_1018.patch
1.21.1 ~ 1.22.xYESproxy_connect_rewrite_102101.patch
1.23.x ~ 1.24.0YESproxy_connect_rewrite_102101.patch
1.25.0 ~ 1.26.xYESproxy_connect_rewrite_102101.patch
1.27.1YESproxy_connect_rewrite_102101.patch

安装

patch -p1 < ngx_http_proxy_connect_module/patch/proxy_connect_rewrite_102101.patch
./configure  --prefix=/usr/local/nginx --with-http_ssl_module --add-module=ngx_http_proxy_connect_module
make && make install

编辑配置文件

server {
    listen                         3128;

    # dns resolver used by forward proxying
    resolver                       114.114.114.114 ipv6=off;

    # forward proxy for CONNECT requests
    proxy_connect;
    proxy_connect_allow            443 80;
    proxy_connect_connect_timeout  10s;
    proxy_connect_data_timeout     10s;

    # defined by yourself for non-CONNECT requests
    # Example: reverse proxy for non-CONNECT requests
    location / {
        proxy_pass http://$host;
        proxy_set_header Host $host;
    }
}

启动nginx后测试

./sbin/nginx
curl -I https://juejin.cn/ -v -x 127.0.0.1:3128

* About to connect() to proxy 127.0.0.1 port 3128 (#0)
*   Trying 127.0.0.1...
* Connected to 127.0.0.1 (127.0.0.1) port 3128 (#0)
* Establish HTTP proxy tunnel to juejin.cn:443
> CONNECT juejin.cn:443 HTTP/1.1
> Host: juejin.cn:443
> User-Agent: curl/7.29.0
> Proxy-Connection: Keep-Alive
> 
< HTTP/1.1 200 Connection Established
HTTP/1.1 200 Connection Established
...

开启防火墙端口

firewall-cmd --zone=public --permanent --add-port=3128/tcp
firewall-cmd --reload

其它无法联网的服务器启用代理

vim /etc/profile
 
#编辑/etc/profile文件 在最后一行加入
export http_proxy=192.168.0.88:3128
export https_proxy=192.168.0.88:3128
#192.168.0.88:3128为你的代理服务器ip和端口

#设置不需要代理的地址
export no_proxy="127.0.0.1,192.168.0.0/24,*.xxx.com"