基本介绍

Nginx 是一款轻量级的 Web 服务器软件,以其高性能、低内存占用和高并发处理能力而闻名。Nginx 可以充当正向代理、反向代理、负载均衡器等多种角色,能够处理大量的并发连接而不占用过多的系统资源。

使用 Nginx 搭建的正向代理,可以用于统一客户端请求出口、以便在服务端配置 IP 白名单限制等,本文将介绍具体的搭建方法。

搭建过程

1、安装 Nginx

# 以为 CentOS 为例
yum update && yum install -y nginx 

2、nginx.conf 配置

cat > /etc/nginx/nginx.conf <<EOF
worker_processes auto;
pid /var/run/nginx.pid;

events {
    worker_connections  65535;
}

http {
    include /etc/nginx/conf/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;
    error_log /var/log/nginx/error.log;
    sendfile        on;
    keepalive_timeout  65;

    client_max_body_size 100m;

    include /etc/nginx/conf/conf.d/*.conf;
}
EOF

3、default.conf 配置

cat > /etc/nginx/conf.d/default.conf <<EOF
server {
    listen 8118;

    client_max_body_size 0;
    proxy_connect;                                # 启用 CONNECT HTTP 方法
    proxy_connect_allow            443 80;        # 指定 CONNECT 方法可以连接的端口号或范围的列表
    proxy_connect_timeout          60s;           # 指定客户端与代理服务器建立连接的超时时间(HTTP)
    proxy_connect_connect_timeout  60s;           # 指定客户端与代理服务器建立连接的超时时间(HTTPS)
    proxy_connect_read_timeout     60s;           # 指定客户端从代理服务器读取响应的超时时间
    proxy_connect_send_timeout     60s;           # 指定客户端向代理服务器发送请求的超时时间
    proxy_read_timeout             60s;

    resolver 100.96.0.2;                          # 指定 DNS 服务器,否则正向代理时无法解析域名

    location / {
        if ($request_method !~ ^(GET|HEAD|POST|PUT|DELETE|CONNECT)$) {
            return 405;
        }

        proxy_pass $scheme://$http_host;          # 通过内置变量动态获取目标地址,以精简配置
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header Authorization $http_authorization;
        proxy_http_version 1.1;
        proxy_set_header Connection "";

    }
}
EOF

4、启动验证

# 启动 Nginx
nginx -s reload

# 使用代理验证
curl <目标服务地址> -x http://<代理服务 IP>:8118

5、报错解决

在请求时可能出现以下报错:

Received HTTP code 400 from proxy after CONNECT

报错原因是 yum 安装的 Nginx 默认不支持 CONNECT 方法,需要安装 ngx_http_proxy_connect_module 模块,过程如下:

# 安装依赖
yum install -y git patch pcre pcre-devel openssl openssl-devel

# 克隆项目
git clone https://gitee.com/web_design_of_web_frontend/ngx_http_proxy_connect_module.git

# 下载 Nginx 源码并解压
wget http://nginx.org/download/nginx-1.20.1.tar.gz
tar -xzf nginx-1.20.1.tar.gz && cd nginx-1.20.1

# 在 Nginx 源码目录下执行 patch,并指定正确的 patch 文件路径
patch -p1 < /root/ngx_http_proxy_connect_module/patch/proxy_connect_rewrite_1018.patch

# 编译安装 Nginx
./configure \
--prefix=/etc/nginx \
--with-http_ssl_module \
--add-module=/root/ngx_http_proxy_connect_module

make && make install

ln -sf /etc/nginx/sbin/nginx /usr/bin/nginx