公司研發一般在內網環境下,但是開發時需要調用某些第三方接口。
這時可以用一臺服務器做nginx反向代理,然後研發機器修改host文件將域名指向服務器即可實現代理轉發。
但是普通的nginx http反向代理代理https時需要配置證書,我們不可能有第三方接口域名的證書,所以要使用nginx 的stream模塊。
普通的nginx反向代理時第七層代理,而stream模塊是第四層代理,轉發的tcp/ip協議,所以不需要證書。
stream模塊要nginx 1.9.0後纔開始支持,目前nginx-1.17.3默認已經包含此模塊。
但是要實現代理多個接口,需要先解包,分析tcp包中的域名等信息,才能分發請求,所以還要用到ngx_stream_ssl_preread_module模塊,這個模塊官方的發佈包裏面沒有包含,需要自行編譯。
nginx 配置文件
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
#gzip on;
server {
listen 80;
server_name i.bosity.com;
location / {
proxy_pass http://i-bosity-com.oss-cn-hongkong.aliyuncs.com;
#proxy_http_version 1.1;
#proxy_set_header Upgrade $http_upgrade;
#proxy_set_header Connection $connection_upgrade;
}
}
include /etc/nginx/conf.d/*.conf;
}
stream {
log_format proxy '$proxy_protocol_addr $remote_addr [$time_local] '
'$protocol $status $bytes_sent $bytes_received '
'$session_time "$upstream_addr" '
'"$upstream_bytes_sent" "$upstream_bytes_received" "$upstream_connect_time"';
#access_log /usr/local/nginx/logs/access.log proxy;
#error_log /usr/local/nginx/logs/error.log info;
map_hash_bucket_size 64;
map $ssl_preread_server_name $backend_pool {
i.bosity.com server_cn;
default server_baidu;
}
upstream server_cn{
server i-bosity-com.oss-cn-hongkong.aliyuncs.com:443;
}
upstream server_baidu{
server 127.0.0.1:443;
}
server{
listen 443;
ssl_preread on;
proxy_pass $backend_pool;
proxy_connect_timeout 15s;
proxy_timeout 15s;
proxy_next_upstream_timeout 15s;
}
}