Post

Nginx 如何进行正向代理

Nginx 如何进行正向代理

什么是正向代理和反向代理

正向代理

假设我们现在要访问Google,但因为众所周知的原因,我们的请求发不出去。此时我们在本地配置了一个代理服务器IP,比如 192.168.1.100。当我们输入 www.google.com 时,请求并没有直接发向谷歌,而是发给了这台代理服务器,由它代替我们去请求谷歌,再把结果传回给我们。

这样做的话有个特点,对于谷歌的服务器来说,它只知道是 192.168.1.100 这个IP在访问它,完全不知道背后其实是你(或者成千上万个像你一样的用户)在发起请求。这就是正向代理,它隐藏了客户端,主要解决的是客户端“访问难”或者“想隐身”的问题。

反向代理

然而反向代理的逻辑完全不同。假设你是淘宝的运维,每天有10亿次请求涌入。你不可能只用一台服务器来扛,肯定是由成百上千台服务器组成的集群。但对于用户来说,他们只知道 www.taobao.com 这一个域名。用户输入网址后,请求首先到达的是反向代理服务器(比如Nginx),然后由它根据负载情况,把请求分发给集群中比较空闲的某一台服务器。

Nginx引入了反向代理机制。反向代理代表的是服务端集群,负责的是流量的调度和保护。用户(客户端)只知道反向代理的地址,完全不知道具体是哪台服务器处理了他的订单。这也保证了后端架构的安全性和高可用性,不会因为某一台服务器的崩溃而导致整个服务不可用。

配置脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
wget https://github.com/chobits/ngx_http_proxy_connect_module/archive/refs/tags/v0.0.2.zip
unzip v0.0.2.zip

wget http://nginx.org/download/nginx-1.19.2.tar.gz
tar xf nginx-1.19.2.tar.gz

cd nginx-1.19.2
patch -p1 < /root/nginx/ngx_http_proxy_connect_module-0.0.2/patch/proxy_connect_rewrite_1018.patch

# this is install on CentOS
yum install gcc cmake make cmake unzip ncurses-devel gcc gcc-c++ pcre pcre-devel -y
./configure --prefix=/usr/local/nginx --add-module=/root/nginx/ngx_http_proxy_connect_module-0.0.2
make && make install 
ln -s /usr/local/nginx/sbin/nginx /usr/local/bin/nginx

# create if you want log
mkdir -p -m 755 /var/log/nginx/

# configure nginx_conf
cd /usr/local/nginx/conf/
cp nginx.conf{,.bak}

vim nginx.conf

配置 nginx.conf

```plain text user ubuntu; worker_processes auto;

#error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info;

pid /run/nginx.pid; events { worker_connections 10240; }

http {

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
sendfile on;
tcp_nopush on;
include 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;
error_log /var/log/nginx/error.log;


#keepalive_timeout  0;
keepalive_timeout 65;

gzip on;

server {
    listen 8000;

    # dns resolver used by forward proxying
    resolver 8.8.8.8 1.1.1.1 208.67.222.222 223.5.5.5;

    # forward proxy for CONNECT request
    proxy_connect;
    proxy_connect_allow 443 563;
    proxy_connect_connect_timeout 10s;

    # forward proxy for non-CONNECT request
    location / {
        proxy_pass http://$host;
        proxy_set_header Host $host;
    }
} } ```
This post is licensed under CC BY 4.0 by the author.