nginx代理访问外网

确认nginx版本

nginx -v
nginx version: nginx/1.21.5

由于Nginx默认不支持HTTPS代理,我们需要额外添加模块。使用的模块是ngx_http_proxy_connect_module。使用模块前需请确保模块和Nginx版本匹配。

下载模块

wget https://github.com/chobits/ngx_http_proxy_connect_module/archive/refs/tags/v0.0.7.tar.gz

安装patch

yum install patch

下载nginx源码包

wget https://nginx.org/download/nginx-1.26.3.tar.gz

解压nginx源码并进入nginx目录

tar xf /tmp/nginx-1.26.3.tar.gz -C /root/
cd /root/nginx-1.26.3/

导入patch

patch -p1 < /root/ngx_http_proxy_connect_module-0.0.7/patch/proxy_connect_rewrite_102101.patch
patching file src/http/ngx_http_core_module.c
patching file src/http/ngx_http_parse.c
patching file src/http/ngx_http_request.c
Hunk #1 succeeded at 1156 (offset 54 lines).
Hunk #2 succeeded at 1809 with fuzz 1 (offset 63 lines).
Hunk #3 succeeded at 2116 (offset 43 lines).
patching file src/http/ngx_http_request.h
Hunk #1 succeeded at 417 (offset 3 lines).
patching file src/http/ngx_http_variables.c

编译nginx

./configure --prefix=/usr/local/nginx --add-module=/root/ngx_http_proxy_connect_module-0.0.7
make && make install

创建配置文件

server {
listen 3928;
resolver 223.5.5.5 valid=300s ipv6=off;
resolver_timeout 30s;
#server_name localhost;
proxy_connect;
proxy_connect_allow 443 80;
proxy_connect_connect_timeout 60s;
proxy_connect_read_timeout 60s;
proxy_connect_send_timeout 60s;

location / {
#proxy_ssl_server_name on;
proxy_set_header Host $host;
proxy_pass $scheme://$http_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;

}
}

创建systemd配置文件

echo "[Unit]
Description=The NGINX HTTP and reverse proxy server
After=network.target
Wants=network.target
[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s stop
PrivateTmp=true
[Install]
WantedBy=multi-user.target" | sudo tee /etc/systemd/system/nginx.service

启动服务

systemctl enable nginx
systemctl start nginx
systemctl status nginx

验证代理

curl -I https://blog.csdn.net/ -v -x 127.0.0.1:8080
文章作者: 慕容峻才
文章链接: https://www.acaiblog.top/nginx代理访问外网/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 阿才的博客
微信打赏
支付宝打赏