一、准备环境

  1. 基础配置:CentOS-9-Stream

  2. 添加虚拟内存(流量转发机器只有 1G内存,执行 dnf install tree 就会卡住)

1
2
3
4
5
6
7
fallocate -l 2G /swapfile
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile

# 开机自动挂载
echo '/swapfile swap swap defaults 0 0' >> /etc/fstab

二、安装

  1. 添加nginx官方仓库,安装
1
2
3
4
5
6
7
8
9
10
11
cat > /etc/yum.repos.d/nginx.repo << 'EOF'
[nginx-stable]
name=nginx stable repo
baseurl=https://nginx.org/packages/centos/9/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true
EOF

dnf install -y nginx
  1. 确认携带的模块
1
nginx -V 2>&1 | grep -o with-stream

三、配置

  1. 创建四层转发的配置文件夹
1
2
3
mkdir -pv /etc/nginx/{stream.d,logs}
mv /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak
mv /etc/nginx/conf.d/default.conf /etc/nginx/conf.d/default.conf.bak
  1. 配置主配置文件
1
vim /etc/nginx/nginx.conf
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
36
37
38
39
40
user  nginx;
worker_processes 1; # 1c机器,1个worker足够

error_log logs/error.log warn;
pid /run/nginx.pid;

events {
worker_connections 1024;
}

# ===== 4层转发(TCP/UDP) =====
stream {
log_format basic '$remote_addr [$time_local] '
'$protocol $status $bytes_sent $bytes_received '
'$session_time';

access_log logs/stream-access.log basic;

include stream.d/*.conf;
}

# ===== 7层反代(HTTP/HTTPS) =====
http {
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 logs/access.log main;

sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
gzip on;

include http.d/*.conf;
}
  1. 配置4层转发
1
vim /etc/nginx/stream.d/forward.conf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 转发到甲骨文机器,把下面的IP换成你自己的
upstream oracle_http {
server 1.2.3.4:80;
}

upstream oracle_https {
server 1.2.3.4:443;
}

server {
listen 80;
proxy_pass oracle_http;
proxy_timeout 10s;
proxy_connect_timeout 5s;
}

server {
listen 443;
proxy_pass oracle_https;
proxy_timeout 10s;
proxy_connect_timeout 5s;
}
  1. 验证配置、启动、验证端口
1
2
3
nginx -t
systemctl enable --now nginx
ss -untlp