我一般都是使用 nginx 做反向代理 tomcat 和其他應(yīng)用的,其實(shí) nginx 也是支持正向代理的
所謂正向代理就是內(nèi)網(wǎng)用戶通過(guò)網(wǎng)關(guān)訪問(wèn)外部資源,就是電腦上網(wǎng)時(shí)瀏覽器設(shè)置下 http 代理地址訪問(wèn)互聯(lián)網(wǎng)
而反向代理就是外部用戶通過(guò)網(wǎng)關(guān)訪問(wèn)內(nèi)網(wǎng)資源,通俗講就是,你的網(wǎng)站跑在內(nèi)網(wǎng)的 8080 端口,別人能夠通過(guò) 80 端口來(lái)訪問(wèn)它
http 代理配置
# 正向代理上網(wǎng)
server {
listen 38080;
# 解析域名
resolver 8.8.8.8;
location / {
proxy_pass $scheme://$http_host$request_uri;
}
}
瀏覽器配置下代理 IP 和端口,然后訪問(wèn) http://www.ip138.com ,可以發(fā)現(xiàn) IP 已經(jīng)變化了,說(shuō)明生效了
然而訪問(wèn) https 網(wǎng)站卻打不開(kāi),這是由于原生 nginx 只支持 http 正向代理,為了 nginx 支持 https 正向代理,可以打 ngx_http_proxy_connect_module 補(bǔ)丁+ ssl 模塊支持
添加 https 代理模塊
這里需要重新編譯 nginx,需要查看當(dāng)前 nginx 的版本和編譯選項(xiàng),然后去官網(wǎng)下載同版本的 nginx 源碼進(jìn)行重新編譯
/usr/local/nginx/sbin/nginx -V
wget http://nginx.org/download/nginx-1.15.12.tar.gz
tar -zxvf nginx-1.15.12.tar.gz
下載模塊 ngx_http_proxy_connect_module
git clone https://github.com/chobits/ngx_http_proxy_connect_module
打補(bǔ)丁,對(duì) nginx 源碼修改,這一步很重要,不然后面的 make 過(guò)不去
patch -d /root/nginx-1.15.12/ -p 1 < /root/ngx_http_proxy_connect_module/patch/proxy_connect_rewrite
在原有配置后追加模塊,make 后注意不要 install
cd /root/nginx-1.15.12/
./configure --with-http_stub_status_module --with-http_ssl_module --with-file-aio --with-http_realip_module --add-module=/root/ngx_http_proxy_connect_module/
make
mv /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx.bak
cp /root/nginx-1.15.12/objs/nginx /usr/local/nginx/sbin/
更改配置文件如下,然后啟動(dòng)服務(wù)
# 正向代理上網(wǎng)
server {
listen 38080;
# 解析域名
resolver 8.8.8.8;
# ngx_http_proxy_connect_module
proxy_connect;
proxy_connect_allow 443 563;
proxy_connect_connect_timeout 10s;
proxy_connect_read_timeout 10s;
proxy_connect_send_timeout 10s;
location / {
proxy_pass $scheme://$http_host$request_uri;
}
}
總結(jié)
代理感覺(jué)不是很穩(wěn)定,有時(shí)候會(huì)打不開(kāi),尤其是 https 網(wǎng)站。訪問(wèn)國(guó)外網(wǎng)站千萬(wàn)不要這樣搞,這里只是為了熟悉下 nginx 的正向代理功能
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。