Run the WebSocket server on a private address such as 127.0.0.1:8080, put Nginx in front of it, terminate TLS at Nginx, and explicitly forward the HTTP/1.1 upgrade headers. Clients then connect to wss://example.com/ws/; Nginx passes the handshake upstream and creates a long-lived tunnel after the application returns 101 Switching Protocols.
Need a server to try this on? Antihost offers Linux VPS plans with NVMe storage, full root access and a 14-day free trial.
This arrangement keeps the application port off the public internet while exposing the normal HTTPS port. It works well for browser-based game services, lobby servers, live dashboards, and any other application that needs a persistent bidirectional connection.
As an Amazon Associate I earn from qualifying purchases.
How the connection is laid out
A WebSocket connection starts as an HTTP request. The client asks to switch protocols by sending an Upgrade header, and the server agrees with an HTTP 101 Switching Protocols response. After that response, the connection is no longer ordinary request-and-response HTTP; it becomes a bidirectional stream.
Nginx can proxy this transition, but the upgrade headers are hop-by-hop headers. They are not forwarded automatically, so the WebSocket location must set them explicitly. Nginx also needs an HTTP/1.1 upstream connection for the handshake. Once the proxied application returns status 101 and the client requested an upgrade, Nginx enters tunnel mode.
#1 Best Overall
- 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.
The resulting path is:
- The browser or game client connects to
wss://example.com/ws/. - Nginx accepts TCP 443, presents the certificate for
example.com, and decrypts TLS. - Nginx sends the request to the application listening on an internal address such as
127.0.0.1:8080. - The application validates the path and handshake and returns 101.
- Nginx relays frames in both directions until either side closes the socket or an idle timeout is reached.
The public URL and the internal listener do not have to use the same port. Keeping the application on localhost or a private interface means clients cannot bypass the proxy and its TLS, logging, and access controls.
Requirements before editing Nginx
- A VPS with Nginx installed and permission to edit its active configuration.
- A WebSocket application that is already listening on a known internal address and port.
- A public DNS name pointing to the VPS.
- A certificate and private key whose hostname matches that public name.
- TCP 443 allowed through the VPS firewall. TCP 80 is useful for certificate issuance and HTTP-to-HTTPS redirects.
- The exact WebSocket route, including whether it ends with a slash. In the examples below, that route is
/ws/.
First verify the application independently. Confirm which process owns the listener, which interface it binds to, and which path it expects. If Nginx and the application are on the same VPS, bind the application to localhost or another private interface rather than exposing its port publicly. The proxy should be the component accepting internet traffic.
Reference Nginx configuration
Put the map in the global http context, not inside a server or location block. Put the WebSocket location in the TLS-enabled server block that answers for your hostname.
# In the http{} block
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
location /ws/ {
proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
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_read_timeout 3600s;
}
}
Replace example.com, the certificate paths, the internal port, and the location path with the values used by your service. Keep the path in the client URL, the Nginx location, and the application route consistent.
Why the conditional map is used
$http_upgrade contains the value supplied by the client. When it is present, the map sets $connection_upgrade to upgrade; when it is empty, the map sets it to close. This prevents ordinary HTTP requests handled by the same location from receiving an inappropriate Connection: upgrade header.
Rank #2
- 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
If a location is dedicated exclusively to WebSockets, a fixed proxy_set_header Connection upgrade; is acceptable. The mapped form is safer whenever normal HTTP requests might also reach that location or when configuration is likely to be reused.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
What each directive does
| Directive | Purpose | Important detail |
|---|---|---|
proxy_pass |
Selects the upstream application. | Use the internal listener. The URI and trailing-slash form affect the path sent upstream. |
proxy_http_version 1.1 |
Uses HTTP/1.1 for the upstream handshake. | Nginx upstream connections otherwise default to HTTP/1.0 in common configurations, which is unsuitable for this upgrade. |
proxy_set_header Upgrade $http_upgrade |
Forwards the client’s requested protocol switch. | Nginx does not pass this hop-by-hop header automatically. |
proxy_set_header Connection $connection_upgrade |
Tells the upstream whether to switch protocols. | The map supplies upgrade only when the client requested it. |
proxy_set_header Host $host |
Preserves the public hostname. | Applications use it for URL generation, host validation, and origin-related checks. |
X-Real-IP and X-Forwarded-For |
Carry the originating client address through the proxy. | The application must be configured to trust forwarded headers only from the proxy. |
X-Forwarded-Proto $scheme |
Tells the application whether the public request used HTTP or HTTPS. | This prevents secure public URLs from being generated as plain HTTP URLs. |
proxy_read_timeout |
Sets the maximum interval Nginx waits between upstream reads. | The documented default is 60 seconds. A quiet socket needs a longer value or application heartbeats. |
Understanding proxy_pass path behavior
With location /ws/ and proxy_pass http://127.0.0.1:8080; as shown, Nginx forwards the original request URI, including /ws/. That is correct when the application itself listens on that route. If the application expects a different path, change the proxy configuration deliberately and test both slash forms.
A trailing slash in a proxy_pass URL changes how Nginx replaces the matching location prefix. Accidentally changing from a host-and-port form to a URI form can turn a valid handshake into a 404. Treat the public path and upstream path as separate values and document the intended mapping.
Deploy the configuration safely
- Confirm the backend. Check that the application process is running, listening on the intended address and port, and configured for the expected WebSocket path.
- Place the map. Add the
map $http_upgrade $connection_upgradeblock inside Nginx’shttpcontext. Defining it inside a location will fail configuration validation. - Add or edit the TLS server block. Set the correct
server_name, certificate paths, andlocation /ws/. Ensure this location is in the HTTPS server block, not only in the port-80 redirect block. - Check the effective configuration. Run the configuration-test command provided by your Nginx installation (on standard installations this is commonly
nginx -t). Fix every syntax or include-file error before reloading. - Reload Nginx. Use the service manager for your distribution so existing connections are not needlessly terminated. If the reload fails, restore the last known-good file and inspect the Nginx error log.
- Connect through the public name. Use
ws://only for an intentionally unencrypted HTTP deployment. Usewss://example.com/ws/when the page or client is delivered over HTTPS. - Watch both logs. Observe Nginx access and error logs and the application log during the first handshake. The logs show whether the request reached Nginx, which upstream was selected, and whether the application accepted it.
A successful upgrade appears as HTTP status 101. The status alone is not a complete health check: keep the connection open long enough to exchange application messages and verify that the application sees the expected client identity and scheme.
TLS, DNS, and firewall layout on a VPS
The public hostname must resolve to the VPS, and the certificate’s hostname must match the name used by the client. A certificate for a different name can make the TLS connection fail before Nginx ever processes the WebSocket request.
Rank #3
- 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)
Expose TCP 443 for the service. Keep TCP 80 available when your certificate process needs it or when you redirect plain HTTP to HTTPS. Do not expose the backend port merely because Nginx uses it; allow that port only when another trusted component genuinely requires access.
When an HTTPS page opens a socket, use wss://. Browsers generally block an insecure ws:// connection from a secure page as mixed content. If HTTPS works for ordinary pages but the socket fails, verify that the WebSocket location exists in the certificate-bearing server block and that the client URL uses wss://.
Testing the handshake
Test from the client side
Use a WebSocket-capable client, browser developer tools, or the client built into your game service. Confirm that the request targets the exact public path and includes an Upgrade request. A normal HTTP request to /ws/ is not equivalent to a WebSocket handshake and may exercise the mapped close branch instead.
Record the observed status and timing. A 101 response means the protocol switch was accepted. A response that immediately closes after 101 points to application-level behavior, a heartbeat policy, or a timeout rather than a missing initial upgrade.
Test from the VPS
Check the internal listener separately from the public endpoint. Confirm that the process is bound to the address in proxy_pass and that a local firewall is not rejecting Nginx. A backend that works from one interface but not from the address Nginx uses can produce a 502 even though the process appears healthy.
Rank #4
- 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
Then test the public hostname so DNS, TLS selection, the server block, and the WebSocket location are exercised together. Perform this test while tailing both logs; the first error line is usually more useful than a later client-side disconnect message.
Troubleshooting by symptom
Handshake returns 400 or closes immediately
- Verify that the client actually sent an Upgrade request rather than an ordinary HTTP request.
- Confirm
proxy_http_version 1.1is present in the active location. - Check both explicit headers:
Upgrade $http_upgradeandConnection $connection_upgrade. - Confirm that the application accepts the requested path and any origin or host validation it performs.
- Compare the Nginx error log with the application log; 400 is a symptom, not proof of one particular cause.
502 Bad Gateway
- Verify that the backend process is running.
- Check the address and port in
proxy_passagainst the process’s actual listener. - Check local firewall rules and private-network policy.
- Make sure the proxy scheme is correct for the backend. A plain internal HTTP listener should use
http://; selecting a scheme the application does not speak will fail before a handshake. - Inspect the Nginx error log for connection-refused, timeout, or name-resolution details.
404 during the handshake
A 404 usually means the request reached a server but the selected route does not exist. Compare the client path, the Nginx location, and the backend route character for character. Check leading and trailing slashes and whether proxy_pass is rewriting the location prefix. Also confirm that DNS selected the intended virtual host rather than a different server block.
Free tools Windows power users keep installed
One-click scans. No signup required.
504 or a disconnect after roughly one minute
Nginx’s documented default is a 60-second interval between upstream reads. A quiet WebSocket can therefore be closed even when both endpoints are healthy. Raise proxy_read_timeout to a value appropriate for the service, as the example does with 3600s, or send periodic WebSocket ping frames from the application. A longer proxy timeout does not replace application-level liveness detection; the client and server should still decide how to detect a dead peer.
Works over HTTP but not HTTPS
- Check that the certificate hostname matches the public name.
- Use
wss://from an HTTPS page. - Verify that the TLS server block, not only the port-80 block, contains the WebSocket location.
- Confirm that TCP 443 reaches this VPS and that another virtual host is not answering first.
The application sees the wrong IP or scheme
Nginx sends the original address through X-Real-IP and X-Forwarded-For, and the public protocol through X-Forwarded-Proto. Configure the application framework to trust those headers only when requests come from your Nginx proxy. Trusting arbitrary client-supplied forwarded headers can corrupt logs, URL generation, and access checks.
Keeping long-lived game connections reliable
WebSocket reliability has two layers. Nginx must keep the tunnel open, while the application must determine whether a peer is alive and what to do when it disappears. Set a read timeout that exceeds the longest expected quiet period, then use application ping/pong traffic when the protocol or game design requires faster failure detection.
Best Value
- 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.
Plan client reconnect behavior separately from the proxy. A reconnecting client should target the same public wss:// URL, and the application should decide whether a new connection resumes a session, creates a new session, or must authenticate again. Nginx does not provide session recovery or message replay; it only transports the upgraded stream.
Monitor connection counts, handshake status, upstream errors, and disconnect timing. A sudden rise in 502 responses points toward the backend or network path; repeated 101 responses followed by one-minute closes point toward idle handling; a rise in 400 responses points toward request construction, path, or application validation.
Configuration choices and trade-offs
| Choice | Use it when | Trade-off |
|---|---|---|
Conditional map |
A location may receive both upgraded and ordinary requests. | Requires a global http-context block but avoids sending upgrade semantics to normal HTTP. |
Fixed Connection upgrade |
The location is exclusively for WebSockets. | Simpler, but unsuitable if ordinary requests later share that location. |
Long proxy_read_timeout |
Connections can remain quiet for long periods. | Quiet dead sockets consume resources longer unless the application also checks liveness. |
| Application heartbeats | You need faster dead-peer detection or an idle intermediary may close the path. | Creates periodic traffic and must be implemented consistently by clients and servers. |
| Private backend binding | Nginx and the application share a VPS or private network. | Improves exposure control, but local connectivity and firewall rules must be correct. |
Operational checklist
- The application listens on the address and port named in
proxy_pass. - The public DNS name resolves to the VPS.
- The certificate covers that exact name.
- TCP 443 is reachable; TCP 80 is available when redirect or certificate workflows need it.
- The
mapis inhttp, and the WebSocket location is in the active TLS server block. - The upstream uses HTTP/1.1.
- The Upgrade and Connection headers are explicitly set.
- The Host and forwarded headers match the application’s trusted-proxy configuration.
- The location and backend route agree on slashes and prefixes.
- The read timeout or heartbeat policy covers the expected idle period.
- Nginx configuration testing passes before every reload.
- Logs are watched during a real public handshake, and status 101 is observed.
What a healthy deployment looks like
A client resolves the public hostname, completes TLS on port 443, requests /ws/ with the HTTP/1.1 upgrade headers, and receives 101. Nginx forwards the same protocol switch to the private application, preserves the host and forwarding information, and then relays frames. The backend port remains inaccessible from the internet, while Nginx’s read timeout and the application’s heartbeat policy determine how quiet connections are handled.
If that sequence breaks, classify the failure by layer: DNS or firewall, TLS, virtual-host selection, path routing, upstream reachability, handshake headers, or idle policy. Checking the corresponding log at each layer is faster and more reliable than changing several directives at once.
Quick Recap
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.
Recommended Free Tools




