Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
VGSources
Blog

How to Set Up a Telegram Bot Webhook on a VPS

A complete guide to hosting a Telegram bot webhook on a VPS: configure IPv4 DNS and a supported port, terminate TLS with Nginx, register a secret HTTPS path, validate requests, verify delivery, and fix common failures.
Length11 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The reliable pattern is simple: point a DNS name at your VPS, run the bot on a private localhost port, terminate TLS at Nginx (normally on port 443), forward one unguessable path to the bot, register that HTTPS URL with setWebhook, and verify delivery with getWebhookInfo. Telegram sends JSON Update objects to that endpoint. It will not use getUpdates polling while an outgoing webhook is active.

What a Telegram webhook does

A webhook changes the delivery model from pulling to pushing. With polling, your process repeatedly asks Telegram for updates. With a webhook, Telegram makes an HTTPS POST request to your VPS whenever an update is available. Your application must accept the JSON-serialized Update body, return a successful HTTP response promptly, and move slow work to an internal queue or background worker.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The public request should terminate at a reverse proxy. Nginx handles the internet-facing TLS connection and forwards only the webhook route to a bot process listening on a private address such as 127.0.0.1:8080. The bot port itself does not need to be exposed by the VPS firewall.

Polling and webhooks are mutually exclusive

An active outgoing webhook prevents getUpdates from being used for the same bot. If you need to return to polling for development or recovery, call deleteWebhook first, then start the polling process. Conversely, stop the polling process before registering a webhook; otherwise the two delivery models conflict and updates may not arrive where you expect.

#1 Best Overall
Sale
Gaoye Blue Light Blocking Glasses
  • BLUE LIGHT BLOCKING GLASSES: Our blue light glasses for women boast UV400 protection, blocking harmful blue rays from computer screens. With these bluelight glasses women, you can enjoy gaming, reading, or watching TV with no worries of eye strain.
  • EYE RELIEF: Our blue light glasses are engineered to reduce blurry vision or strain caused by prolonged screen time. These womens blue light glasses aid in better sleep by preventing blue light from disrupting your natural sleep cycle, helping you fall asleep faster and enjoy a more restful night's sleep, making them the perfect christmas present.
  • COMFORTABLE: Crafted from durable material, our trendy blue light glasses for woman or blue light glasses men ensure long-lasting comfort. The high-transmittance lenses accessories, gamer gifts for men, help keep your eyes relaxed. Perfect stocking stuffers, gifts for gamers men, christmas gifts for men, halloween costumes.
  • LIGHTWEIGHT: These clear blue light glasses feature a lightweight frame, meaning they’ll stay comfy for long-term wear. Perfect as blue blockers glasses for women or mens blue light glasses, these non-prescription fake glasses for men can be worn throughout the day. The blue light blocking glasses women feature polycarbonate HD lenses, which are anti-reflective and restore true color.
  • WORRY-FREE PURCHASE: If you experience any issues, our support team is ready to assist you quickly. These are the perfect costume glasses for cosplay dressing up.

Requirements before you configure anything

Requirement What to prepare Why it matters
VPS network A public IPv4 address and an inbound firewall rule for one Telegram-supported TCP port Telegram’s webhook service requires IPv4; its current guide does not support IPv6 webhook delivery.
DNS An A record such as bot.example.com pointing to the VPS IPv4 address Telegram connects to the hostname in the webhook URL, not to a private address.
TLS A certificate whose CN or SAN exactly matches the webhook hostname, with the intermediate chain included Telegram requires TLS 1.2 or newer and validates the hostname and certificate chain.
Supported port 443, 80, 88, or 8443 Telegram accepts webhook connections only on these ports. Port 443 is the conventional choice.
Bot service An application route that accepts Telegram JSON POST requests and responds quickly The reverse proxy needs a healthy private upstream to forward each update.
Secrets The bot token, an unguessable URL path, and optionally a secret-token value The path and the X-Telegram-Bot-Api-Secret-Token header provide independent request-authentication checks.

1. Point DNS at the VPS and open the right port

  1. Choose the hostname you will use permanently, for example bot.example.com.
  2. Create an A record for that hostname with the VPS public IPv4 address. Check the record from outside the VPS and confirm that it resolves to the intended address.
  3. Select a supported webhook port. Use 443 unless another port is required by your network design. Allow inbound TCP on that port in both the VPS provider firewall and the operating-system firewall.
  4. Do not publish the bot’s application port, such as 8080, to the internet. Bind it to localhost or an equivalent private interface.

Use the exact hostname from DNS in the eventual webhook URL. A certificate for a different name, even another name on the same server, will not satisfy Telegram’s hostname check.

2. Run the bot privately

Configure the bot framework’s HTTP server to listen on 127.0.0.1:8080 (or another private port) and expose a route dedicated to the secret webhook path. The route should accept POST requests with Telegram’s JSON body and return a success status as soon as the update has been safely accepted. Put database calls, media processing, external API calls, and other slow operations on a queue or background worker instead of making Telegram wait for them.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Run this process under a service manager or container supervisor so it starts after reboot and is restarted after a crash. Keep the bot token and webhook secret in environment variables or a protected secret store. Do not put either value in source control, a public issue, or verbose request logs.

Keep the application route and proxy route identical

If the registered URL ends in /tg/7f3c..., Nginx must forward that same path to the application, or deliberately strip it according to your framework’s routing rules. A mismatch commonly produces a proxy-level 404 even though the bot process itself is running.

3. Terminate TLS with Nginx

Obtain a trusted certificate for the exact DNS name and configure Nginx with the complete certificate chain. Telegram’s webhook guide requires TLS 1.2 or newer, and the certificate CN or SAN must match the supplied domain. The intermediate certificates must be served along with the leaf certificate; installing only the leaf certificate can look valid in a browser while failing Telegram’s validation.

Rank #2
Windex Gaming Cleaning Wipes, Pre-Moistened Wipes to Instantly Clean all Gaming Gear and Electronics, Resealable Packaging for a Freshness Lock, 25 count (Pack of 1)
  • WINDEX GAMING WIPES: effortlessly clean all your gaming gear and gaming electronics in one easy step with our new Windex Gaming Wipes
  • AMMONIA FREE: our ammonia-free formula is safe to use on all of your favorite gaming equipment like consoles, headsets, controllers, screens, keyboards, and more
  • PRE-MOISTENED WIPES: each wipe instantly removes dust, dirt, and stubborn smudges and fingerprints leaving a streak-free shine
  • ANTI-STATIC: great for cleaning and wiping down your gaming gear and electronics leaving behind no visible residue
  • COMPACT RESEALABLE PACKAGE: store your pack of Windex Gaming Wipes anywhere in your home for whenever a quick and easy wipedown is needed

A minimal server block looks like this (replace the certificate paths, hostname, private upstream port, and secret path with your values):

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
server {
    listen 443 ssl;
    server_name bot.example.com;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_certificate /path/to/full-chain.pem;
    ssl_certificate_key /path/to/private-key.pem;

    location /tg/long-random-path {
        proxy_pass http://127.0.0.1:8080;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Proto https;
    }
}

Test the Nginx configuration before reloading it, then confirm that it is listening on the selected port. The webhook endpoint must be served directly over HTTPS. Telegram’s FAQ states that redirects are not supported, so do not register an HTTP URL that depends on an HTTP-to-HTTPS redirect. Register the final HTTPS URL instead.

Using a non-standard supported port

Ports 80, 88, and 8443 are also supported, but the port must appear in the webhook URL when it is not the default for the scheme, and the same port must be open through every firewall layer. The certificate and hostname requirements still apply. Changing ports does not remove the need for TLS; Telegram documents that webhook encryption is required regardless of the selected port.

4. Register the webhook with the Bot API

Choose a path that is long and unguessable. It is an additional barrier because a random internet client that does not know the path should not be able to reach the bot route. Treat the bot token as a password and avoid placing it in shell history or shared process listings.

For a trusted certificate, call setWebhook with the complete HTTPS URL:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
LISEN Cell Phone Stand Phone Holder for Desk, Office Decor Gadgets for Men
  • Ergonomic & Adjustable Design: Fight "text neck" and improve your posture. Designed for comfort, it offers an adjustable height (7.1in-8.5in) (1.4in adjustable range) and angle (5°-85°) Please note: cell phone stand is only 9 inches tall—the length of a standard pencil
  • Without blocking subtitles Perfect for office desk Tiktok Face Time Zoom video—this is the ultimate kitchen desk essential for phones! Perfect viewing experience while reducing neck back strain, A must-have for gamers streamers desk, and anyone who values both style and support!
  • Sleek & Stable Design fits Otterbox Case: Say goodbye to bent cables, tangles, and tip-overs! LISEN’s stylish adjustable desk phone holder features a built-in charging hole and smart cable management, keeping your phone secure and your workspace clutter-free cool gadgets for men
  • ANTI-SLIP DESIGN free hands: The under 10.00 items easy gadgets back and the bottom of this kitchen essentials for women are fully covered by anti-skid silicone, which LISEN stand up desk decor can provide maximum protection device from any scratches and slides
  • Your Perfect Viewing Companion:If your product arrives damaged or breaks within 365 days, reach out to LISEN for a quick and hassle-free solution. Struggling with assembly, like tightening the screw? We’ve got your back! Your experience matters to us. (Product including: phone Holder stand*1, screw*1, hexagon screwdriver*1, specification*1)
curl -F 'url=https://bot.example.com/tg/long-random-path' 
  'https://api.telegram.org/botYOUR_BOT_TOKEN/setWebhook'

Telegram responds with a success result when the webhook is accepted. A successful registration only means that Telegram accepted the configuration; it does not prove that DNS, the firewall, Nginx routing, and the application response all work end to end. Perform the verification steps below before considering the deployment complete.

Registering with a self-signed certificate

A self-signed certificate can be used when its public certificate is uploaded during registration. Supply the public PEM file with the certificate parameter:

curl -F 'url=https://bot.example.com/tg/long-random-path' 
  -F '[email protected]' 
  'https://api.telegram.org/botYOUR_BOT_TOKEN/setWebhook'

Telegram’s self-signed certificate instructions specifically require uploading the certificate through the certificate parameter. Keep the private key only on the VPS; the uploaded file must be the public certificate.

5. Authenticate incoming requests

Use two checks at the application boundary:

  • Route only the unguessable path through Nginx. Return a not-found response for other paths rather than exposing a generic bot endpoint.
  • Set a secret_token when registering the webhook and require the matching X-Telegram-Bot-Api-Secret-Token header on every request. The Bot API accepts a secret-token value from 1 to 256 characters.

Generate the value randomly, store it outside the source code, and compare the received header using your framework’s constant-time comparison function where available. Reject a missing or incorrect header before doing expensive JSON processing. Never write the header value to access logs, exception reports, or analytics.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

An unguessable path is not a replacement for the header check: paths can leak through logs or configuration exports. The header is not a replacement for TLS: without HTTPS, a network observer could read it. Use both controls.

Rank #4
Ledagic IC+RGBW USB Powered Led Light Bar with App & Remote Control, 2 Pack
  • Easy Installation: Our gaming lights have been designed to enhance your entertainment experience. Simply position the led light bar next to your TV or game console to create a game room environment with ease. They come with USB power and a 60 inch cord for direct mounting and mobility
  • Audio Syncing & Extensive Mode: The built-in high-sensitivity music sensor allows you to sync the TV led lights to your favorite music. Lights react and move to the beat of music, film and game audio, creating an incredible immersive sound and light experience – and all without the need for an additional hub. You can choose from 64+ patterns, including strobe, illusion, jump, energy, gradient, running, chasing, fluttering mode etc. Each mode can be applied to different scenes
  • 64+ Chasing IC+RGB & W Effect: The independent control design of IC+RGB and white all-in-one multifunctional rgbw led bar lights monitor backlight allows you to easily switch the led lights for desk between IC+RGB and white to enjoy a variety of lighting effects, you can choose white lighting mode with high brightness for better illumination when working, etc. Choose IC+RGB lighting mode when you need to create an entertaining atmosphere for the light show, 16 million colours of Color changing rgb light bar let you dance to the beat and create a dynamic party atmosphere
  • Dynamic and Dimmable Lights: 1%-full brightness free brightness adjustment gives you the flexibility to adjust dimmable led light bar for room decorations or a variety of occasions
  • USB Powered: USB light bars for room can be powered by powernank, usb charger, TV, Monitor, laptop PC mainframe, making behind TV led lighting bar easy to install in any location.TV led lights are powered by the TV usb interface / PC mainframe, can be turned on/off synchronously with TV / PC

6. Verify the configuration and delivery

Query the webhook status with:

curl 'https://api.telegram.org/botYOUR_BOT_TOKEN/getWebhookInfo'

Inspect these fields in the returned object:

  • url — the exact endpoint Telegram is using. Confirm the scheme, hostname, port, and path.
  • pending_update_count — updates waiting to be delivered. A growing value indicates that Telegram cannot complete delivery or the application is not acknowledging requests fast enough.
  • last_error_date and last_error_message — the most recent delivery failure and its diagnostic text.
  • max_connections — the configured webhook connection limit.
  • allowed_updates — the update types Telegram is configured to send.

Send a message to the bot from a test account while watching both the Nginx access/error logs and the bot’s application log. You should see a POST at the exact secret path, a successful upstream response, and the update handled by the application. Test a second message after restarting the bot service to confirm that the process supervisor and startup configuration work.

Webhook capacity and connection settings

The Bot API permits max_connections from 1 to 100, with a default of 40. This is a Telegram API limit, not a promise that the VPS or application can process that many requests concurrently. Start with the default unless measured workload and application capacity justify a change. Raising the value without enough workers, database connections, or memory can increase queueing and failures.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Setting Allowed or default value Operational meaning
max_connections 1–100; default 40 Upper bound for Telegram’s simultaneous webhook connections for the bot.
secret_token 1–256 characters Value Telegram places in the X-Telegram-Bot-Api-Secret-Token header.
Webhook ports 443, 80, 88, 8443 Ports Telegram accepts for webhook delivery; TLS remains required.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshoot by symptom

setWebhook is rejected with a certificate or hostname error

Issue or install a certificate whose CN or SAN exactly contains the webhook hostname. Check that Nginx serves the certificate for the intended server_name, not a default virtual host. If the certificate is valid but Telegram still cannot build a trust chain, configure the full chain including intermediate certificates. For a self-signed setup, upload the public PEM certificate with certificate when calling setWebhook.

The endpoint returns a redirect

Remove the redirect from the registered webhook route. Telegram does not follow redirects for webhook requests. Register the final HTTPS URL and make Nginx serve that URL directly. This includes avoiding a trailing-slash redirect caused by a route that exists only with or without the slash.

No request reaches Nginx

Start with getWebhookInfo. If last_error_message indicates a connection or timeout problem, verify the DNS A record from an external network, confirm that the VPS has the expected public IPv4 address, and check every firewall layer. Ensure the selected port is one of 443, 80, 88, or 8443 and that Nginx is listening on it. Do not rely on an IPv6-only DNS record; Telegram’s current webhook guidance requires IPv4.

Best Value
Sale
HUANUO FlowLift™ Dual Monitor Stand, Fully Adjustable Gaming Monitor Desk Mount for 13–32″ Computer Screens, Full Motion VESA 75x75/100x100 with C-Clamp & Grommet Base, Each Arm Holds 4.4 to 19.8 lbs
  • Compatible with Wide Screens - To ensure compatibility with the dual monitor mount, your each monitor must meet three conditions at the same time: First, computer screens size range: 13 to 32 inches. Second, screen weight range: 4.4 to 19.8 lbs. Third, the back of the monitor screen must have VESA mounting holes with a pitch of 75x75mm or 100x100mm.
  • Regarding the compatibility with desks - Your desk must meet three conditions at the same time: First, desk material: Only wooden desks are recommended, plastic or glass desks cannot be used. Second, desk thickness range: 0.59" - 3.54". Third, the bottom of the desk should not have any cross beams or panels, as this will interfere with installation. We recommend carefully checking that your desk and monitors meets all above conditions before purchasing.
  • Dual C-Clamp Hold - Worried your dual monitors might wobble or slip? Our upgraded base uses a larger platform plus a dual C-clamp structure to lock the dual monitor arm firmly to your desk. Each arm safely keeps your screens steady while you type, click and game—no shaking, no sliding, just a clean and secure setup you can trust every day. It also provides Grommet Mounting installation choice, both options ensure stable and secure fixation for your 0.59" - 3.54" desk.
  • Full-Motion Adjustment For Comfortable View - Pull the screen closer when you’re deep in a spreadsheet, push it back to watch videos, or rotate to portrait for coding — moving everything smoothly with just one hand. The monitor stand offers +85°/-50° tilt, ±90° swivel and 360° rotation. Raise your monitor up to 15.75″ to support a healthy sitting posture. Whether you’re working from home, gaming through the night, or switching between video calls and documents, getting the screens to your natural line of sight helps relieve neck, shoulder and back strain so you can stay focused longer with less fatigue.
  • Keep Your Desk Organized: By lifting both screens off the desktop, this dual monitor stand opens up valuable space for your keyboard, notebook, docking station or a simple, clutter-free work area. Built-in cable management guides wires along the arms, keeping cords out of sight and out of the way. Enjoy a tidy, modern workstation that looks as good as it feels to use.

Nginx receives the request but the bot returns 404

Compare the path in getWebhookInfo.url, the Nginx location, and the application route character by character. Check whether proxy_pass is preserving or replacing the URI, and inspect the Nginx error log for an upstream address or configuration mistake. A request sent to the hostname root will not prove that the secret route works.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Nginx returns 502 or 504

Confirm that the bot process is running and listening on the same private address and port used in proxy_pass. Test the upstream locally from the VPS, then inspect the application log for crashes during JSON parsing or startup. A 502 usually indicates that Nginx cannot connect to the upstream; a timeout commonly means the process accepted the request but did not respond promptly.

The webhook is configured, but updates remain pending

Read pending_update_count, last_error_date, and last_error_message together. A rising pending count with certificate or connection errors points to DNS, TLS, firewall, or proxy routing. A healthy connection with slow or failed application responses points to the bot process, its dependencies, or insufficient concurrency. Return a success response after safely queuing the update, and move long-running work out of the request handler.

The bot appears to receive nothing after switching from polling

Stop every polling worker and check whether an old webhook still exists. If you intentionally want polling, call deleteWebhook before starting getUpdates. If you want webhooks, leave polling disabled, call setWebhook again with the correct URL, and verify the resulting url field.

The secret-header check fails

Confirm that the value supplied as secret_token during registration is the same value loaded by the application. Compare the exact bytes, including case and punctuation, and make sure a proxy or middleware is not removing the X-Telegram-Bot-Api-Secret-Token header. Rotate the value by registering a new secret and updating the application configuration in a coordinated restart.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choosing an operating pattern

Pattern TLS and exposure Operations to plan
Nginx with an automated trusted certificate Public 443 with a hostname-matching certificate and full chain Renewal, Nginx reloads, service restart policy, access/error log rotation, and upstream health checks.
Nginx with a self-signed certificate Public supported port with the public PEM uploaded through setWebhook Protect and renew the private key, upload the new public certificate when it changes, and keep the certificate and webhook configuration synchronized.
Another reverse proxy Any Telegram-supported port with equivalent TLS and hostname behavior Preserve the webhook path, forward the POST body and secret header, return prompt upstream responses, and provide restart and logging controls.
Containerized bot behind a proxy Only the proxy is public; the container joins a private network Use a stable internal service name or address, persist secrets safely, define restart behavior, and ensure the proxy waits for the bot to become ready.

The implementation can vary, but the externally visible contract does not: Telegram must resolve the hostname to your IPv4 VPS, complete TLS without a redirect, reach a supported port, receive the expected path, and get a timely successful response.

Security and maintenance checklist

  • Keep the bot token out of shell history, source control, screenshots, and logs.
  • Use a long random path and enforce the secret-token header.
  • Expose only the reverse-proxy port; bind the bot server to localhost or a private network.
  • Serve the complete certificate chain and renew the certificate before expiry.
  • Do not add an HTTP redirect in front of the registered webhook URL.
  • Limit Nginx logging so request bodies and authentication headers are never recorded.
  • Monitor pending_update_count, last_error_message, process restarts, and proxy 4xx/5xx responses.
  • Keep the application handler short and queue slow work.
  • After changing DNS, certificates, paths, ports, or secrets, run getWebhookInfo and send a real test message.
  • Document whether the bot uses webhook delivery or polling so a maintenance script cannot start the wrong mode.

Final end-to-end checklist

  1. The DNS A record resolves the webhook hostname to the VPS public IPv4 address.
  2. The selected port is 443, 80, 88, or 8443 and is open through all firewalls.
  3. Nginx (or the chosen proxy) presents a matching certificate with its intermediate chain and TLS 1.2 or newer.
  4. The proxy serves the final HTTPS URL directly, without a redirect.
  5. The bot listens privately and the proxy forwards the exact secret path to it.
  6. setWebhook has been called with the correct URL, and the optional secret token is configured in both Telegram and the application.
  7. getWebhookInfo shows the expected URL and no current delivery error.
  8. A real test message produces a POST in the proxy log and a handled update in the application log.
  9. No polling worker is running while the webhook remains active.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.