Enabling Secure WebSocket Connections to Yjs Collaborative Editor with .htaccess

Abstract: Resolve Yjs WebSocket connection failures on Apache by correctly configuring .htaccess to proxy wss traffic using mod_proxy_wstunnel.

Created: 2026-10-11 by

Securing Yjs WebSocket connections requires configuring Apache’s .htaccess to proxy wss:// traffic over standard HTTPS. This setup ensures that collaborative editing sessions are encrypted in transit, preventing man-in-the-middle attacks and ensuring data integrity for real-time document synchronization.

The Problem with Insecure WebSockets

WebSockets provide a persistent, full-duplex communication channel between the client browser and the server. For Yjs, this is critical because every keystroke, selection change, and cursor movement must be transmitted instantly to all connected collaborators. When you use an insecure ws:// connection, this data travels in plain text. On public networks or even within untrusted local networks, attackers can intercept these packets, potentially reading sensitive document content or injecting malicious instructions into the collaboration session. While many developers default to Nginx for reverse proxying due to its performance characteristics, Apache remains a popular choice for shared hosting environments and specific deployment configurations where .htaccess files offer granular, per-directory control without requiring root access to modify the main server configuration. The previous approach failed because it incorrectly attempted to rewrite the protocol scheme directly in the target URL of the RewriteRule, which violates how mod_proxy handles upstream connections. The proxy module expects a valid HTTP/HTTPS URL to connect to the backend Node.js process, not a WebSocket URI.

Configuring Apache for Secure Proxying

To correctly route secure WebSocket traffic through Apache, you must enable two specific modules: mod_rewrite for handling the connection upgrade headers and mod_proxy_wstunnel for tunneling the WebSocket frames. Without mod_proxy_wstunnel, Apache will treat the WebSocket handshake as a standard HTTP request and fail to establish the persistent connection, resulting in immediate disconnection errors in the Yjs client console. Create or edit the .htaccess file in the directory where your Yjs frontend assets are served. You need to define rules that identify the WebSocket endpoint and redirect it to your local Node.js server running on a different port, such as 3000 or 8080. The core logic involves checking the Upgrade header. If the client requests an upgrade to WebSocket, Apache must pass this request to the backend while maintaining the security context provided by the SSL certificate. The following configuration demonstrates the correct syntax for this redirection.
# Enable Rewrite Engine
RewriteEngine On

# Check if the connection is upgrading to WebSocket
RewriteCond %{HTTP:Upgrade} websocket [NC]
RewriteCond %{HTTP:Connection} upgrade [NC]

# Proxy the request to the local Node.js server using http://
# Note: Use http:// for the internal connection, even if the external is wss://
RewriteRule ^/yjs-ws/(.*)$ http://localhost:3000/$1 [P,L]
It is crucial to understand why we use http://localhost:3000 instead of wss://localhost:3000 in the RewriteRule target. The P flag tells Apache to proxy the request. The connection between the client and Apache is secured via TLS (WSS), but the connection between Apache and your Node.js application is typically internal. Unless your Node.js app itself is configured with a self-signed certificate and you have explicitly set up mutual TLS, using http:// for the internal hop is standard practice. Apache handles the termination of the WSS connection from the client and forwards the raw WebSocket frames to the backend over plain HTTP.

Handling CORS and Security Headers

Beyond routing, you must ensure that your Apache instance allows the cross-origin requests required by Yjs. Collaborative editors often serve their frontend from one domain and their API/WebSocket endpoints from another, or they rely on dynamic origins. Add the following headers to your .htaccess to permit necessary cross-origin interactions.
# Allow Cross-Origin Requests
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "GET, POST, OPTIONS"
Header set Access-Control-Allow-Headers "Content-Type, Authorization, Upgrade, Connection"
The Upgrade and Connection headers are particularly important here. If these are blocked by strict CORS policies, the browser will refuse to initiate the WebSocket handshake before it even reaches Apache. While setting Access-Control-Allow-Origin to * is convenient for development, production environments should restrict this to the specific domains hosting your editor interface. This restriction helps prevent unauthorized third-party sites from initiating connections to your Yjs server. For deeper insights into securing your broader infrastructure, consider reviewing strategies for Securing an Ubuntu Server for Development Purposes, which covers firewall configurations and user permissions that complement web server settings. Additionally, understanding how to manage network-level security is vital when exposing services like this; see Understanding Ubuntu 22.04 VPS Security for best practices on hardening your host environment against direct attacks.

Verifying the Setup

After updating your .htaccess file, restart Apache to apply the changes. You can verify the module loading status by running apache2ctl -M | grep proxy in your terminal. Ensure both proxy_module and proxy_wstunnel_module are listed. To test the connection, open your browser’s developer tools and navigate to the Network tab. Filter by WebSocket. Connect to your Yjs editor. You should see a request with a Status Code of 101 Switching Protocols. The URL in the browser bar should display wss://, confirming that the encryption is active end-to-end from the browser to the Apache proxy. If you see a 404 or 502 error, check your Apache error logs for messages related to mod_proxy failures, which usually indicate misconfigured backend addresses or disabled modules. Properly securing your WebSocket layer ensures that your collaborative documents remain private and tamper-proof. By correctly implementing the proxy rules in .htaccess, you leverage Apache’s robust handling of HTTP upgrades while maintaining the simplicity of managing configuration at the directory level.

Frequently Asked Questions

Why does my WebSocket connection fail with a 400 Bad Request?

This error typically occurs when the Upgrade or Connection headers are missing or incorrectly formatted in the initial handshake. Ensure that your .htaccess rules correctly capture these headers using [NC] flags and that your CORS settings explicitly allow them in the Access-Control-Allow-Headers directive.

Can I use wss:// in the RewriteRule target for internal proxies?

No, using wss:// in the target of a RewriteRule with the P flag is technically invalid for mod_proxy. The proxy module expects a standard HTTP or HTTPS URL to connect to the upstream backend. Use http:// for internal connections unless you have specifically configured mutual TLS between Apache and your Node.js app.

How do I debug WebSocket issues in Apache?

Enable detailed logging by adding LogLevel debug to your Apache configuration or virtual host settings. Check the error.log file for entries prefixed with proxy_wstunnel. These logs will reveal whether the handshake was received, upgraded successfully, or dropped due to header mismatches.

Is it safe to expose Yjs WebSockets directly without a proxy?

Exposing WebSockets directly without a reverse proxy can complicate SSL management and make it harder to enforce consistent security headers. A proxy like Apache or Nginx centralizes SSL termination, allowing you to manage certificates centrally and protect your backend Node.js server from direct exposure to the internet.

What happens if mod_proxy_wstunnel is not enabled?

If mod_proxy_wstunnel is missing, Apache will attempt to handle the WebSocket request as a standard HTTP GET request. It will likely return a 400 Bad Request or 404 Not Found error because it cannot process the Upgrade header correctly, causing the Yjs client to fail to establish a persistent connection.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More