nginx正向代理-为内网提供外网代理服务
1.背景
当内网服务需要访问外网时,苦于机器没有外网访问权限,若给所有机器开放外网权限,成本高、风险不可控,介于此我们是不是可以提供几台物理机做转发访问外网,内网有外网访问需求,通过内网代理机即可,我们这里使用nginx正向代理实现(nginx介于客户端和服务器之间)
2.nginx配置
里面有两份配置,对应两个端口:8080 和 8043 分别用于代理 http 和 https
server { listen 8080; underscores_in_headers on; resolver 8.8.8.8; resolver_timeout 5s; if ($http_x_forwarded_for = '') { set $varxff $remote_addr; } if ($http_x_forwarded_for != '') { set $varxff $http_x_forwarded_for; } location / { proxy_connect_timeout 5s; proxy_read_timeout 120s; proxy_send_timeout 120s; proxy_max_temp_file_size 0; proxy_buffering on; proxy_buffer_size 16k; proxy_buffers 4 64k; proxy_busy_buffers_size 128k; proxy_temp_file_write_size 128k; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $varxff; proxy_set_header cookie $http_cookie; proxy_set_header Proxy-Connection ""; proxy_set_header X-Bd-Safe-Host ""; proxy_http_version 1.1; if ($http_x_bd_product = "image") { proxy_pass $scheme://$host$request_uri; break; } if ($http_x_bd_safe_host ~ "^(\d{1,3}\.){3}\d{1,3}(:\d{2,5})?$") { proxy_pass $scheme://$http_x_bd_safe_host$request_uri; break; } proxy_pass $scheme://$http_host$request_uri; } } server { listen 8443; underscores_in_headers on; resolver 8.8.8.8; resolver_timeout 5s; set $product ""; set $subsys ""; if ($http_x_forwarded_for = '') { set $varxff $remote_addr; } if ($http_x_forwarded_for != '') { set $varxff $http_x_forwarded_for; } location / { proxy_connect_timeout 5s; proxy_read_timeout 120s; proxy_send_timeout 120s; proxy_max_temp_file_size 0; proxy_buffering on; proxy_buffer_size 16k; proxy_buffers 4 64k; proxy_busy_buffers_size 128k; proxy_temp_file_write_size 128k; proxy_ssl_server_name on; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $varxff; proxy_set_header cookie $http_cookie; proxy_set_header Proxy-Connection ""; proxy_http_version 1.1; proxy_pass https://$http_host$request_uri; } }
完事后nginx restart 或 reload即可
3.使用
curl使用方式:
curl -x ip:port 方式指定代理
示例:
http请求: curl -v -x 127.0.0.1:8080 http://www.baidu.com https请求: curl -v -x 127.0.0.1:8443 http://www.baidu.com 注意原地址的https请求不加s,nginx会自动加上
wget使用方式:
wget -e http_proxy=127.0.0.1:8080 方式指定代理
示例:
http请求: wget -O tmp.tgz -e http_proxy=127.0.0.1:8080 http://www.baidu.com https请求: wget -O tmp.tgz -e http_proxy=127.0.0.1:8443 http://www.baidu.com
业务代码访问可参考以上设置访问。