Node.js+Express+Socket.io+Apache反向代理出现404错误求助
Alright, let's fix that Socket.io 404 error you're seeing behind Apache reverse proxy. Here's what's going on and how to fix it step by step:
Why the 404 Happens
Your Apache config only forwards requests under /chatApp to your Node.js server, but Socket.io is trying to hit /socket.io/ (its default path) — that request isn't being proxied, hence the 404. Even though you pointed your client to https://server.com/chatApp, Socket.io needs explicit path configuration on both the server and proxy side to work correctly with a subpath.
Step 1: Update Your Socket.io Server Config
In your Node.js/Express code, tell Socket.io to listen on the /chatApp/socket.io path to align with your proxy's subpath:
const express = require('express'); const http = require('http'); const { Server } = require('socket.io'); const app = express(); const server = http.createServer(app); // Add the path option to match your proxy subpath const io = new Server(server, { path: '/chatApp/socket.io' }); // Your existing Socket.io logic here... server.listen(3000);
Step 2: Adjust Apache Reverse Proxy Rules
Add a new rule to forward Socket.io-specific requests to your Node server. Update your Apache config like this:
# Original proxy rule for your app ProxyPass /chatApp http://localhost:3000/ ProxyPassReverse /chatApp http://localhost:3000/ # New rule for Socket.io traffic ProxyPass /chatApp/socket.io http://localhost:3000/socket.io ProxyPassReverse /chatApp/socket.io http://localhost:3000/socket.io
Also, make sure you have the required Apache modules enabled (critical for both HTTP polling and WebSocket support):
a2enmod proxy a2enmod proxy_http a2enmod proxy_wstunnel
Then restart Apache to apply changes:
systemctl restart apache2 # Use `service apache2 restart` if on older systems
Step 3: Keep Your Frontend Code As-Is
Your existing client initialization is correct:
var socket = io("https://server.com/chatApp");
With the server and proxy configs updated, the client will now automatically request https://server.com/chatApp/socket.io/, which gets properly forwarded to your Node server.
After making these changes, restart both your Node.js app and Apache, then refresh your browser — the 404 error should be gone!
内容的提问来源于stack exchange,提问作者Hari Ram

