Nginx配置正向代理http/https案例

Nginx正向代理配置案例如下:

编辑nginx.conf文件,配置正向代理

#HTTP
server {
    #定义域名解析,可配置多个
    resolver 8.8.8.8 114.114.114.114;
    #用于指定dns解析的超时时间
    resolver_timeout 20s;

    listen 0.0.0.0:8888;

    access_log  /data/log/nginx/nginx.proxy.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 50;
        proxy_send_timeout 60;
        proxy_read_timeout 60;

        proxy_cache_valid 200 302 10m;
        proxy_cache_valid 301 1h;
        proxy_cache_valid any 1m;
   }
}

#HTTPS
server{
         #定义域名解析,可配置多个
         resolver 8.8.8.8 114.114.114.114;
         #用于指定dns解析的超时时间
        resolver_timeout 20s;
        access_log /data/log/nginx/nginx.proxy.log main;
        listen 443;
        location / {
                root html;
                index index.html index.htm;
                proxy_pass https://$host$request_uri;
                proxy_buffers 256 4k;
                proxy_max_temp_file_size 0k;
                proxy_connect_timeout 50;
                proxy_send_timeout 60;
                proxy_read_timeout 60;
                proxy_next_upstream error timeout invalid_header http_502;
        }
        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
                root html;
        }
}

客户端增加代理访问

如上正向代理配置完成后,在浏览器或者程序中配置代理,其中浏览器配置代理如下:
代理配置

验证代理访问

查看Nginx访问日志 /data/log/nginx/nginx.proxy.log 验证是否正常代理,例子如下表示已经过代理服务器转发

 - -[18/Jan/2019:14:01:31 +0800] "CONNECT fonts.googleapis.com:443 HTTP/1.1" 200 598 "-" "-"
 - - [18/Jan/2019:14:01:31 +0800] "CONNECT static.cnblogs.com:443 HTTP/1.1" 200 598 "-" "-"
 - - [18/Jan/2019:14:01:31 +0800] "CONNECT pic.cnblogs.com:443 HTTP/1.1" 200 598 "-" "-"
.......

参考地址:http://nginx.org/en/docs/http/ngx_http_core_module.html#resolver