nginx正向代理(http)
环境
- 外网服务器(CentOS Linux release 7.5.1804 (Core))
- 内网服务器
步骤
一、在外网服务器上部署nginx
1.安装需要的环境依赖
yum -y install wget gcc gcc-c++ pcre-devel zlib-devel
2.下载nginx源码包
wget http://nginx.org/download/nginx-1.19.0.tar.gz
3.安装nginx
[root@localhost ~]# ls
nginx-1.19.0.tar.gz
[root@localhost ~]# tar xf nginx-1.19.0.tar.gz
[root@localhost ~]# ls
nginx-1.19.0 nginx-1.19.0.tar.gz
[root@localhost ~]# cd nginx-1.19.0
[root@localhost nginx-1.19.0]# ls
auto CHANGES.ru configure html man src
CHANGES conf contrib LICENSE README
[root@localhost nginx-1.19.0]# ./configure && make && make install
4.添加环境变量
export PATH=$PATH:/usr/local/nginx/sbin
5.启动
[root@localhost nginx-1.19.0]# cd /usr/local/nginx/
[root@localhost nginx]# nginx
[root@localhost nginx]# ss -nltp|grep 80
LISTEN 0 128 *:80 *:* users:(("nginx",pid=13717,fd=6),("nginx",pid=13716,fd=6))
二、配置正向代理服务器
1.修改配置文件
vim conf/nginx.conf
server {
resolver 8.8.8.8;
resolver_timeout 5s;
listen 0.0.0.0:8080;
access_log /home/reistlin/logs/proxy.access.log;
error_log /home/reistlin/logs/proxy.error.log;
location / {
proxy_pass $scheme://$host$request_uri;
proxy_set_header Host $http_host;
proxy_buffers 256 4k;
proxy_max_temp_file_size 0;
proxy_connect_timeout 30;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 301 1h;
proxy_cache_valid any 1m;
}
}
2.检测配置文件是否正确
nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
3.重载
nginx -s reload
三、配置内网服务器
1.修改yum配置文件
vim /etc/yum.conf
IP地址为正向代理服务器IP
端口为正向代理的监听端口
proxy=http://ip:port
四、测试
1.使用yum进行安装
yum -y install gcc
结果:安装成功
2.关闭正向代理服务器的网卡重新测试
正向代理服务器操作
ifdown ens33
内网服务器操作
yum -y install gcc-c++
结果:下载失败
配置说明
1.配置 DNS 解析 IP 地址,比如 Google Public DNS,以及超时时间(5秒)。
resolver 8.8.8.8;
resolver_timeout 5s;
2.配置正向代理参数,均是由 Nginx 变量组成。其中 proxy_set_header 部分的配置,是为了解决如果 URL 中带 “.”(点)后 Nginx 503 错误。
proxy_pass
s
c
h
e
m
e
:
/
/
scheme://
scheme://host$request_uri;
proxy_set_header Host $http_host;
3.配置缓存大小,关闭磁盘缓存读写减少I/O,以及代理连接超时时间。
proxy_buffers 256 4k;
proxy_max_temp_file_size 0;
proxy_connect_timeout 30;
4.配置代理服务器 Http 状态缓存时间。
proxy_cache_valid 200 302 10m;
proxy_cache_valid 301 1h;
proxy_cache_valid any 1m;
注意事项
因为 Nginx 不支持 CONNECT,所以无法正向代理 Https 网站(网上银行,Gmail)。
如果访问 Https 网站,比如:https://www.google.com,Nginx access.log 日志如下:
“CONNECT www.google.com:443 HTTP/1.1” 400
原文链接
https://www.cnblogs.com/inteliot/archive/2013/01/11/2855907.html
https://blog.youkuaiyun.com/qq_49296785/article/details/109391411