Telegram Bot Webhook Nginx Reverse Proxy Configuration Guide: SSL, Paths, and Timeout Pitfalls
关于作者
TG-Staff 致力于为 Telegram Bot 运营团队提供高效、可靠的客服与营销 SaaS 工具。
Telegram Bot Webhook Nginx Reverse Proxy Configuration Guide: SSL, Path, and Timeout Pitfalls
When deploying a Telegram Bot, Webhook is the most direct way to receive user messages, but it has strict HTTPS requirements. Many teams encounter issues such as SSL certificate errors, 502 timeouts, and path truncation when configuring Nginx as a reverse proxy. This article provides a step-by-step guide from zero to a production-ready Nginx configuration, along with a troubleshooting checklist and common issues. It is suitable for B2B SaaS operations and community management teams.
Why Does a Telegram Bot Need Nginx Reverse Proxy?
The Telegram Bot Webhook mechanism requires your server to be exposed over HTTPS, typically listening on port 443. While it is possible to have the bot backend (e.g., Python Flask, Node.js Express) listen on port 443 and handle SSL certificates directly, there are several practical pain points:
- The backend service may also serve internal APIs and should not be exposed to the public.
- Multiple bots may need to share the same public IP and domain.
- Operational tasks such as SSL certificate renewal, logging, and rate limiting require a unified entry point.
Nginx reverse proxy solves these problems: it handles SSL termination, path forwarding, and load balancing, while the backend service only listens on internal ports, significantly reducing operational complexity.
Webhook’s Mandatory Requirements for SSL and Port
The Telegram API only accepts HTTPS connections with TLS 1.2 or higher, and the Webhook URL must be publicly accessible on port 443 or 80 (in production, almost exclusively port 443). If the certificate chain is incomplete, the domain name mismatches, or the protocol version is too low, Telegram will reject the connection and return a "SSL certificate is invalid" error.
Reverse Proxy vs. Direct Bot Server Connection: When to Choose Nginx
| Scenario | Direct Bot Server | Nginx Reverse Proxy |
|---|---|---|
| Single bot, low traffic, temporary testing | Feasible, simple | Unnecessary |
| Multiple bots, multiple domains, centralized SSL management | High operational cost | Recommended |
| Rate limiting, IP whitelisting, log auditing | Requires custom implementation | Natively supported by Nginx |
| Backend service also needs to serve internal network | Exposure risk | Secure isolation |
Conclusion: If your bot serves B-end customers, requires multi-user collaboration, or manages multiple bots, Nginx reverse proxy is a more reliable choice.
Prerequisites: What Information and Components Do You Need?
Before configuring, ensure the following elements are ready:
- Bot Token: Obtain from @BotFather, formatted like
123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11. - Domain: Resolved to your server IP, e.g.,
bot.yourdomain.com. - Backend Service Address: The IP and port your bot backend listens on, e.g.,
127.0.0.1:3000. - Nginx Installed: Version recommended ≥ 1.18.
- SSL Certificate: Let’s Encrypt is recommended (free, auto-renewal); commercial certificates are also acceptable.
- Server Firewall: Allow port 443 (via
ufw allow 443/tcpor cloud platform security group rules).
Step 1: Configure Nginx Site – SSL Certificate and Webhook Path Forwarding
Assume your domain is bot.yourdomain.com, the backend service runs on 127.0.0.1:3000, and the Webhook path is /webhook/<bot_token>. Below is a complete Nginx server block example:
server {
listen 443 ssl;
server_name bot.yourdomain.com;
ssl_certificate /etc/letsencrypt/live/bot.yourdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/bot.yourdomain.com/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
location /webhook/ {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 30s;
proxy_read_timeout 60s;
proxy_send_timeout 60s;
}
access_log /var/log/nginx/bot-access.log;
error_log /var/log/nginx/bot-error.log;
}
Save the above content to /etc/nginx/sites-available/bot.yourdomain.com, then create a symbolic link to sites-enabled, run nginx -t to test the syntax, and if no errors, execute systemctl reload nginx.
Key proxy_set_header Parameters Explained
- Host $host: Passes the original Host header; Telegram verifies the domain matches the certificate.
- X-Real-IP $remote_addr: Records the client’s real IP; the backend can use this header to obtain the user’s IP.
- X-Forwarded-For $proxy_add_x_forwarded_for: Chains proxy IPs for auditing.
- X-Forwarded-Proto $scheme: Indicates the original protocol (https); the backend can determine if TLS was used.
Missing these headers may result in backend logs showing only Nginx’s internal IP, or Webhook signature verification failures.
Path Rewriting: Avoid Webhook Path Truncation
The location /webhook/ block matches all requests starting with /webhook/. If the backend expects the path to be /webhook/<token> without any additional prefix, the above configuration is sufficient. However, if the backend listens on the root path (/), you need to use rewrite to remove the path prefix:
location /webhook/ {
rewrite ^/webhook/(.*) /$1 break;
proxy_pass http://127.0.0.1:3000;
}
This way, /webhook/123456:ABC is forwarded as /123456:ABC. Adjust according to your backend’s actual routing, otherwise you may receive a 404.
Step 2: Resolve HTTPS Certificate Issues – Let’s Encrypt Auto-Renewal
Let’s Encrypt certificates are valid for 90 days and require automatic renewal. Use Certbot’s webroot mode to complete verification while Nginx is running:
certbot certonly --webroot -w /var/www/html -d bot.yourdomain.com
After renewal, run systemctl reload nginx to make the new certificate effective. It is recommended to configure a cron job:
0 0 * * * certbot renew --quiet --renew-hook "systemctl reload nginx"
If you use standalone mode, you must temporarily stop Nginx, which is not recommended for production environments.
TLS Version Compatibility Recommendations
Telegram API requires TLS 1.2 or higher. Explicitly specify ssl_protocols TLSv1.2 TLSv1.3; in your Nginx configuration and disable SSLv3/TLSv1.0/TLSv1.1 to pass security audits.
Step 3: Handling 502 Bad Gateway—Timeout and Backend Health Checks
502 is the most common reverse proxy error, typically caused by the following:
- Backend service not started: Use
systemctl status bot-serviceorps aux | grep botto verify the process exists. - Firewall blocking the backend port: Check
ufw statusor the cloud platform’s security group to ensure the backend port (e.g., 3000) is open. - Nginx timeout too short: If the backend takes a long time to process webhook requests (e.g., AI inference, database writes), the default
proxy_read_timeout 60smay be insufficient. Adjust based on your business needs:
proxy_connect_timeout 30s;
proxy_read_timeout 120s; # 延长至 120 秒
proxy_send_timeout 60s;
Common 502 Troubleshooting Checklist (Firewall, Backend Logs, Nginx error.log)
- Check backend service logs: Confirm there are no crashes or connection refusals.
- View Nginx error.log:
tail -f /var/log/nginx/error.logto locate the specific error line. - Test backend directly: Use
curl http://127.0.0.1:3000/healthon the server to verify the backend responds. - Confirm firewall settings:
iptables -L -n | grep 3000orufw status numbered. - Check SELinux/AppArmor: Some systems by default prevent Nginx from proxying to local ports; adjust policies as needed.
Step 4: Verifying Webhook Configuration—curl Test and Telegram API Confirmation
After configuration, set the webhook URL via the Telegram API:
curl -X POST "https://api.telegram.org/bot<YOUR_BOT_TOKEN>/setWebhook" \
-H "Content-Type: application/json" \
-d '{"url": "https://bot.yourdomain.com/webhook/<YOUR_BOT_TOKEN>"}'
On success, it returns {"ok": true, "result": true, "description": "Webhook was set"}.
Then query the webhook status:
curl "https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getWebhookInfo"
Example of a normal response (key fields):
{
"ok": true,
"result": {
"url": "https://bot.yourdomain.com/webhook/123456:ABC",
"has_custom_certificate": false,
"pending_update_count": 0,
"last_error_date": 0,
"last_error_message": "",
"max_connections": 40,
"ip_address": "你的服务器公网IP"
}
}
If last_error_message is not empty (e.g., "SSL certificate is invalid" or "Connection timed out"), it indicates an issue with the Nginx configuration; return to Step 1 to debug.
Production Environment Considerations: Logging, Rate Limiting, and Security Hardening
- Enable Nginx logging: access.log records request sources and status codes; error.log records anomalies. Rotate logs regularly (
logrotate) to prevent disk exhaustion. - Configure rate limiting: Prevent malicious calls to the bot endpoint:
limit_req_zone $binary_remote_addr zone=bot_limit:10m rate=10r/s;
location /webhook/ {
limit_req zone=bot_limit burst=20 nodelay;
proxy_pass http://127.0.0.1:3000;
}
- Disable unnecessary HTTP methods: Allow only POST (Telegram webhook uses POST):
if (request_method !~ ^(POST)) {
return 405;
}
- Restrict IP whitelist (optional): If only fixed Telegram IP ranges access, add the
allowdirective in the location block. However, Telegram IPs change; signature verification is recommended over IP whitelisting. - Regularly check SSL rating: Test with SSL Labs to ensure a rating of ≥ A.
Common Misconception: Webhook Path and Bot Token Leakage
Never expose Bot Token directly in Nginx configuration file comments or logs. It is recommended to use environment variables or separate configuration files to reference the Token, preventing the Bot from being controlled by third parties due to log leakage.
FAQ
Q: Telegram Bot Webhook returns 502 Bad Gateway, how to quickly troubleshoot?
A: First check if the backend Bot service is running normally (systemctl status bot-service or view processes). Then confirm the IP:port in Nginx proxy_pass is correct. Finally check Nginx error.log (usually at /var/log/nginx/error.log) for specific errors—common causes include firewall blocking backend port, proxy_read_timeout too short (recommend ≥ 60s).
Q: Setting Webhook prompts “SSL certificate is invalid”, but the certificate is valid?
A: Three common reasons: 1) Incomplete certificate chain (missing intermediate certificate, need to merge fullchain.pem); 2) Domain name does not match certificate CN/SAN; 3) Nginx ssl_certificate and ssl_certificate_key paths are not correctly configured. Use openssl s_client -connect yourdomain.com:443 -servername yourdomain.com to verify the certificate chain.
Q: Does the Webhook path need to include Bot Token? How to handle it securely?
A: Telegram requires the Webhook URL path to include Bot Token (e.g., https://yourdomain.com/webhook/123456:ABC-DEF) to verify request origin. Best practice: store Token in Nginx variable or external file, import via include directive to avoid plaintext hardcoding in config files. Filter Token fields in logs.
Q: After using Let’s Encrypt certificate, Webhook occasionally fails, why?
A: Possibly because Certbot auto-renewal did not reload Nginx. Add --renew-hook "systemctl reload nginx" after the cron renewal command. Also check if the certificate correctly replaces old files after renewal (sometimes old processes hold old file handles).
Q: How to configure Nginx reverse proxy for multiple Telegram Bots?
A: In the same server block, use different location paths for each Bot (e.g., /webhook/bot1_token and /webhook/bot2_token), proxy_pass to different backend ports. You can also use multiple server_names or subdomains for isolation. Each Bot’s Webhook URL must be unique.
If you manage multiple Telegram Bots for customer service and operations, and don’t want to spend too much effort on Nginx configuration, try TG-Staff—it provides a web console to centrally manage Bot Webhooks and agent conversations, with built-in diversion links, auto-translation, content moderation, etc., saving the operational cost of building your own reverse proxy. Register for a 3-day free trial: https://app.tg-staff.com/. For more Nginx and Bot integration examples, see official docs. For questions, contact @tgstaff_robot for technical support.
Related Articles
Google vs Bing Search Optimization: Only TG, TG Bot, and Telegram Bot Keyword Matrix
Master the search differences between Google and Bing, build a keyword matrix for only TG, TG Bot, and Telegram Bot, and boost SEO rankings. This guide provides actionable long-tail keyword strategies and internal linking plans to help Telegram operations teams acquire precise customers.
Only TG TG Bot Telegram Bot Triangular Keyword SEO Layout: Guide to Avoiding Cannibalization
Avoid SEO cannibalization among Only TG, TG Bot, and Telegram Bot triangular keywords. This article teaches you how to win independent rankings for each keyword on Google and Bing through content planning, page structure, and internal linking strategies, while boosting overall traffic.
TG Bot Multilingual Auto-Translation Complete Guide: From Configuration to Plan Quota Planning
How to configure multilingual auto-translation for your Telegram Bot? This article details TG-Staff's auto-translation features, plan quota comparisons, and planning strategies to help you efficiently manage cross-border customer service teams and enhance user communication experience.