title: 配置nginx正向代理 #标题tags: nginx正向代理 #标签
date: 2020-09-15
categories: nginx # 分类
环境描述:nginx主机一台,可以访问外网,内网主机不能访问外网,但是可以访问nginx。
需求:配置nginx正向代理,代理内网主机访问外网。
Nginx本身不支持HTTPS正向代理,需要安装ngx_http_proxy_connect_module模块后才可以支持HTTPS正向代理,否则会遇到HTTP 400错误。
这里将把配置nginx支持https正向代理从0到1写下来。
接下来的操作,没有特殊说明,在nginx主机上操作即可。
安装相应工具
wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
yum makecache fast
yum -y install gcc gcc-c++ autoconf automake pcre pcre-devel openssl openssl-devel patch git net-tools
下载nginx及第三方模块并编译
第三方模块对应不同的nginx/openresty版本,需要编译不同的文件,请参考下面的图表进行编译:
nginx version | enable REWRITE phase | patch |
---|---|---|
1.4.x ~ 1.12.x | NO | proxy_connect.patch |
1.4.x ~ 1.12.x | YES | proxy_connect_rewrite.patch |
1.13.x ~ 1.14.x | NO | proxy_connect_1014.patch |
1.13.x ~ 1.14.x | YES | proxy_connect_rewrite_1014.patch |
1.15.2 | YES | proxy_connect_rewrite_1015.patch |
1.15.4 ~ 1.16.x | YES | proxy_connect_rewrite_101504.patch |
1.17.x ~ 1.18.0 | YES | proxy_connect_rewrite_1018.patch |
OpenResty version | enable REWRITE phase | patch |
---|---|---|
1.13.6 | NO | proxy_connect_1014.patch |
1.13.6 | YES | proxy_connect_rewrite_1014.patch |
1.15.8 | YES | proxy_connect_rewrite_101504.patch |
# 下载第三方模块并编译
mkdir /opt/nginx_1.18 -p
cd /opt/nginx_1.18
git clone https://github.com/chobits/ngx_http_proxy_connect_module.git
# 下载nginx并编译安装
cd /opt
wget http://nginx.org/download/nginx-1.18.0.tar.gz
tar zxf nginx-1.18.0.tar.gz
cd nginx-1.18.0/
patch -p1 < /opt/nginx_1.18/ngx_http_proxy_connect_module/patch/proxy_connect_rewrite_1018.patch
# nginx 1.18对应的是此版本的第三方模块,具体你的nginx对应的是哪个,请参考上面的表格。
./configure --prefix=/opt/nginx_1.18 --user=nginx --group=nginx --with-http_ssl_module --add-module=/opt/nginx_1.18/ngx_http_proxy_connect_module --with-stream
# 注:上面的--add-module模块指定的是下载的那个仓库目录,而不是上面patch指定的那个文件路径
make && make install
echo $? # 输出 0 表示make install 无误
0
配置nginx
此时即可配置nginx,使其成为正向代理。
cd /opt/nginx_1.18/conf/
vi nginx.conf # 写入以下server字段
server {
listen 3128;
# 指定代理dns
resolver 114.114.114.114;
# forward proxy for CONNECT request
proxy_connect;
proxy_connect_allow all;
proxy_connect_connect_timeout 10s; # 此处是指定各种超时时间,默认为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;
}
}
关于上述配置解释,请参考官方文档。
启动nginx,客户端测试
# 创建nginx运行用户并启动nginx
useradd nginx
cp /opt/nginx_1.18/sbin/nginx /usr/local/bin/
nginx -t
nginx
接下来在无法访问外网的主机上分别使用http及https的请求进行测试。
# 将http代理及https代理写入环境变量并重载配置文件
cat >> /etc/profile << EOF
export http_proxy=192.168.20.5:3128
export https_proxy=192.168.20.5:3128
EOF
source /etc/profile
# 分别下载http链接和https链接进行测试
# 注:下载https连接时可能会报错,多试两次即可
# 猜测是因为3128端口同时代理了http和https,可能会出现冲突
wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.8.0-x86_64.rpm
wget http://nginx.org/download/nginx-1.18.0.tar.gz
https下载时可能会遇到以下情况,多执行几次即可:
其实,如果要长久使用正向代理,还是建议用squid来配置正向代理。