【tgbot api 反代】Telegram机器人api被墙解决办法:自建反代

本文最后更新于:2022年11月4日 下午

如果我们需要在大陆的服务器/网络上使用telegram bot的API,那要么翻墙要么反代。本来可以用CloudFlare的workers进行反代,但前不久它已经被墙了。但是我们可以用自己的国外服务器进行反代。

准备

  • 不受GFW封锁的服务器
  • 一个没有被墙的域名

安装Nginx

这个应该不必说。

1
2
3
4
# Ubuntu或者Debian
apt install nginx
# CentOS或者Red Hat
yum install nginx

配置Nginx

找到你nginx的配置文件,在http{}中加上下面的配置。

目前较新版本的nginx是在 /etc/nginx/conf.d/ 文件夹下。

老一点的版本是在: /etc/nginx/sites-available/ 文件夹下。

新建.conf结尾的文件即可。例如:vim /etc/nginx/conf.d/telebotapi.conf

然后加入下面配置 (记得把 yourDomainName 换成你的域名,有两处):

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
# http强制跳转到htpps
server {
listen 80;
listen [::]:80;
server_name yourDomainName;

# Enforce HTTPS
return 301 https://$server_name$request_uri;
}
## https
server {
listen 443 ssl;
listen [::]:443 ssl;

server_name yourDomainName;

## ssl密钥路径自己改改
#ssl_certificate server.pem;
#ssl_certificate_key server.key;

## root非必要
root /var/www/tgbot/;

## dns必须写,不然会报502错误
resolver 8.8.8.8;

## 以bot开头的请求都会被正则匹配到
location ~* ^/bot {
proxy_buffering off;
proxy_pass https://api.telegram.org$request_uri;
proxy_http_version 1.1;
}

## 和上面root一样非必要,这个主要是用来确认服务器状态的。也可以改成return 403
location /{
try_files /$uri $uri /index.html;
}

## no log no fix
error_log /var/log/tg.log error;
}

yourDomainName-你准备的域名

测试一下语法是否正确:

1
2
3
$ nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

重新加载配置:

1
systemctl reload nginx

🎉然后执行 systemctl restart nginx

安装certbot(申请证书用)

如果已经有证书,直接将Nginx配置文件中ssl_certificate server.pem; ssl_certificate_key server.key; 写入你的证书地址,并取消注释(删除#)即可,那可以跳过本小节。

ssl_certificate-SSL证书路径
ssl_certificate_key-SSL证书路径

不知道的可以参考文章:自动为你的域名申请证书:certbot的安装和使用

使用方式

将原来的 https://api.telegram.org/ 替换为 https://yourDomainName/ ,即可正常推送消息

防止盗用

用防火墙限制访问的源IP

serverIp-你用来访问反代域名的ip地址,你系统安装的那个就用那个命令,ufw iptables 都可。

1
2
3
4
5
#ubuntu
ufw allow proto tcp from serverIp to any port 443
#centos
iptables -I INPUT -p tcp --dport 443 -j DROP
iptables -I INPUT -s serverIp -p tcp --dport 443 -j ACCEPT

但问题是如果你用了反代的服务器建了别的站,会导致别的站不能访问。不过你可以换个端口来反代telegram bot,相应的,防火墙规则也换一个端口就好。

参考文章

本文参考哪吒面板文档:TG api被墙解决方案


【tgbot api 反代】Telegram机器人api被墙解决办法:自建反代
https://pawswrite.xyz/posts/38606.html
作者
Rainbow
发布于
2022年6月3日
许可协议