1. 程式人生 > 實用技巧 >Nginx正向代理

Nginx正向代理

1、下載安裝nginx

# 1、安裝nginx相關依賴
yum -y install gcc pcre pcre-devel zlib zlib-devel openssl openssl-devel
# 2、下載nginx
wget https://nginx.org/download/nginx-1.14.0.tar.gz
# 3、解壓
tar -xzvf nginx-1.14.0.tar.gz
cd nginx-1.14.0
./configure --prefix=/usr/local/nginx  --sbin-path=/usr/bin/nginx --with-http_stub_status_module --with-http_ssl_module
# 4、編譯安裝
make && make install

2、配置Nginx支援https正向代理

# 1、下載ngx_http_proxy_connect_module,該模組主要用於隧道SSL請求的代理伺服器
git clone https://github.com/chobits/ngx_http_proxy_connect_module
# 2、進入解壓nginx-1.14.0解壓後的資料夾下打補丁
patch -p1 < /kay/ngx_http_proxy_connect_module/patch/proxy_connect_1014.patch
# 3、新增ngx_http_proxy_connect_module模組
./configure --prefix=/usr/local/nginx --add-module=/kay/ngx_http_proxy_connect_module --with-http_ssl_module
# 4、編譯
make

# 5、將編譯後的nginx,替換掉之前安裝的nginx;如果未安裝可以直接使用make install進行安裝
cp /kay/nginx-1.14.0/objs/nginx /usr/bin/

3、配置nginx.conf

    server {
        resolver 114.114.114.114;       #指定DNS伺服器IP地址 
        listen 80;
        location / {
            proxy_pass http://$host$request_uri;     #設定代理伺服器的協議和地址 
            proxy_set_header HOST $host;
            proxy_buffers 256 4k;
            proxy_max_temp_file_size 0k;
            proxy_connect_timeout 30;
            proxy_send_timeout 60;
            proxy_read_timeout 60;
            proxy_next_upstream error timeout invalid_header http_502;
        }
    }
    
    server {
        resolver 114.114.114.114;       #指定DNS伺服器IP地址 
        listen 8443;
        proxy_connect;
        proxy_connect_allow 443 563;
        proxy_connect_connect_timeout 10s;
        proxy_connect_read_timeout 10s;
        proxy_connect_send_timeout 10s;
        
        location / {
            proxy_set_header Host $http_host;
            proxy_pass https://$host$request_uri;    #設定代理伺服器的協議和地址 
            proxy_buffers 256 4k;
            proxy_max_temp_file_size 0k;
            proxy_connect_timeout 30;
            proxy_send_timeout 60;
            proxy_read_timeout 60;
            proxy_next_upstream error timeout invalid_header http_502;
        }
    }

4、測試

# https
curl --proxy localhost:8443 https://www.baidu.com
# http
curl --proxy localhost:80 http://www.baidu.com

參考

https://blog.csdn.net/luChenH/article/details/107553493
https://blog.csdn.net/luChenH/article/details/107553493