Reverse Proxy Telegram Bot API
If your Dashboard server cannot access the Telegram Bot API but you still want to send notifications through Telegram, you can try solving the issue with a reverse proxy.
Preparation
This guide describes how to use your own server as the reverse proxy. You can also use Cloudflare Workers, but network connectivity may still be poor for users in mainland China.
To set up a Telegram Bot API reverse proxy, prepare the following:
- A server that can connect to the Telegram Bot API and has NGINX installed.
- A domain name with an SSL certificate issued in advance.
NGINX Configuration
Edit the NGINX configuration file and add the following configuration inside http{}:
# Redirect HTTP to HTTPS
server {
listen 80;
listen [::]:80;
server_name <yourDomainName>;
# Force HTTPS
return 301 https://$server_name$request_uri;
}
# HTTPS configuration
server {
listen 443 ssl;
listen [::]:443 ssl;
server_name <yourDomainName>;
# SSL certificate paths
ssl_certificate </path/to/your/server.pem>;
ssl_certificate_key </path/to/your/server.key>;
# Root is optional
root /var/www/tgbot/;
# DNS resolver is required, otherwise 502 errors may occur
resolver 8.8.8.8;
# Requests beginning with /bot are matched by this regex
location ~* ^/bot {
proxy_buffering off;
proxy_pass https://api.telegram.org$request_uri;
proxy_http_version 1.1;
}
# Root is optional and mainly used to confirm server status. You can also change it to return 403
location / {
try_files $uri $uri /index.html;
}
# Error log
error_log /var/log/tg.log error;
}yourDomainName: the domain name you prepared.ssl_certificate: the SSL certificate path.ssl_certificate_key: the SSL certificate key path.
Usage
Run systemctl restart nginx to restart NGINX. Then replace the original https://api.telegram.org/ in Nezha with https://<yourDomainName>/ to send messages normally.
Prevent Abuse
Configure a firewall to prevent others from abusing your reverse proxy service:
serverIp: the Agent IP address. Choose the command that applies to your system; bothufwandiptablesare acceptable.
# 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 ACCEPTThe configuration above helps prevent unauthorized access.