必备条件

  • 一台能正常访问 TG API 的机器
  • NGINX
  • https

因为请求 TG API 走的是 HTTPS, 所以这里必须要 HTTPS 反代

核心配置

  • 可以自由的把这段 location 添加到已有的 nginx ssl 配置中, 用于实现反代

    不熟悉的 NGINX 的, 加错了自己修

  • 配置检查, 重载: nginx -t && nginx -s reload
1
2
3
4
5
6
7
8
9
10
11
location ~* ^/bot {
## dns必须写,不然会报502错误
resolver 8.8.8.8;
proxy_buffering off;
proxy_pass https://api.telegram.org$request_uri;
proxy_http_version 1.1;
# 不能设置 proxy header 否则无返回
# proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

验证

  • 如果 502 先看看 有没有设置 dns, 检查 dns 可用性
  • 然后再看看 nginx 日志, 根据配置文件排查看看是哪里不对劲
1
2
3
4
❯ curl https://api.telegram.org/bot
{"ok":false,"error_code":404,"description":"Not Found"}#
❯ curl https://tyn3.xxx.xxx/bot
{"ok":false,"error_code":404,"description":"Not Found"}#

完整配置

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
upstream iitii {
server openwrt.iitii.me:443;
}
server {
listen 80 default_server;
rewrite ^(.*) https://$host$1 permanent;
}
server {
listen 443 ssl;
server_name china.iitii.me;
ssl on;
ssl_certificate /etc/nginx/ssl/china.iitii.me/pem.pem;
ssl_certificate_key /etc/nginx/ssl/china.iitii.me/key.key;
ssl_session_timeout 5m;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_protocols TLSv1.1 TLSv1.2 TLSv1.3;
location ~* ^/bot {
## dns必须写,不然会报502错误
resolver 8.8.8.8;
proxy_buffering off;
proxy_pass https://api.telegram.org$request_uri;
proxy_http_version 1.1;
# 不能设置 proxy header 否则无返回
# proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location / {
proxy_pass https://iitii;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Real_IP $remote_addr;
proxy_set_header User-Agent $http_user_agent;
proxy_set_header Accept-Encoding '';
proxy_buffering off;
}
}

参见