本文主要内容转载自:https://ryanz.de/archives/33.html,感谢 ryanz 大佬的教程指导。

本文仅作备份之用,无意侵占或剽窃原作者成果。

教程适用于使用1panel反代的方式,证书为公开 CA 签发的免费证书。

Cloudflare内设置:

  • 点击域名——网络——开启 gRPC和WebSockets。

  • SSL/TLS——概述——将SSL/TLS加密模式改为完全。

  • 将域名托管至Cloudflare后开启小黄云。

1Panel 域名配置文件

打开 1Panel 你添加的哪吒面板域名——配置文件,加上代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 定义真实 IP 变量
map $http_x_real_ip $temp_ip {
"" $http_cf_connecting_ip;
default $http_x_real_ip;
}
map $temp_ip $temp_ip2 {
"" $http_x_forwarded_for;
default $temp_ip;
}
map $temp_ip2 $real_ip {
"" $remote_addr;
default $temp_ip2;
}

# 允许头部包含下划线
underscores_in_headers on;

# 定义上游服务器
upstream dashboard {
keepalive 512;
server 127.0.0.1:8008;
}

如果你使用的是其它面板(比如宝塔)或程序,完整的配置文件结构应该是这样的:

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
http {
# 其他全局配置...

# 真实 IP 获取
map $http_x_real_ip $temp_ip {
"" $http_cf_connecting_ip;
default $http_x_real_ip;
}
map $temp_ip $temp_ip2 {
"" $http_x_forwarded_for;
default $temp_ip;
}
map $temp_ip2 $real_ip {
"" $remote_addr;
default $temp_ip2;
}

# 允许头部包含下划线
underscores_in_headers on;

# 定义上游服务器
upstream dashboard {
keepalive 512;
server 127.0.0.1:8008;
}

# 其他全局配置...

server {
# server配置...

# 反向代理配置(location块)...
}
}

1Panel 域名反向代理源文

域名——反向代理——源文,使用下面的配置替换:

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
41
42
43
44
location ^~ / {
proxy_pass http://127.0.0.1:8008;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $real_ip;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header X-Forwarded-Proto $scheme;
proxy_http_version 1.1;
proxy_read_timeout 1800s;
proxy_send_timeout 1800s;
proxy_buffer_size 128k;
proxy_buffers 4 128k;
proxy_busy_buffers_size 256k;
proxy_max_temp_file_size 0;
add_header X-Cache $upstream_cache_status;
add_header Cache-Control "private, no-store";
proxy_ssl_server_name on;
}

# gRPC 服务
location ^~ /proto.NezhaService/ {
grpc_set_header Host $host;
grpc_set_header X-Real-IP $real_ip;
grpc_read_timeout 600s;
grpc_send_timeout 600s;
grpc_socket_keepalive on;
client_max_body_size 10m;
grpc_buffer_size 4m;
grpc_pass grpc://dashboard;
}

# WebSocket 服务
location ~* ^/api/v1/ws/(server|terminal|file)(.*)$ {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $real_ip;
proxy_set_header Origin https://$host;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 1800s;
proxy_send_timeout 1800s;
proxy_pass http://127.0.0.1:8008;
}

面板后台设置

  • 前端真实 IP 请求头设置为 X-Real-IP

  • Agent 真实 IP 请求头设置为 X-Real-IP

无论是否开启 CDN 都无需修改任何设置,因为我们通过 Nginx 的 map 指令动态确定了 X-Real-IP 头部的值。

至此,所有设置完成。

这个统一配置的好处是简化了管理,不需要在切换 CDN 状态时手动修改 Nginx 配置和哪吒面板设置,系统会自动选择正确的 IP 来源。