Making Socket.io path work with NGiNX proxy_pass

1.1k Views Asked by At

I would like to use NGiNX to proxy pass the following:

https://something.com/node.js/foo/bar/baz

into this:

https://something.com:3000/foo/bar/baz

I have successfully done it with the following NGiNX config:

location ~ /node.js/(.*) {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-NginX-Proxy true;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "";

    add_header Cache-Control "public";

    proxy_set_header   X-Forwarded-Host   $host;
    proxy_set_header   X-Forwarded-Server $host;
    proxy_set_header   X-Forwarded-For    $proxy_add_x_forwarded_for;

    proxy_http_version 1.1;
    proxy_pass http://127.0.0.1:3000/$1$is_args$args;
}
location / {
    try_files $uri /index.php$is_args$args;
}

The problem is the following: when I instantiate socket.io with the default path, it serves socket.io.js here:

https://something.com/node.js/socket.io/socket.io.js

So far so good, but then this javascript tells the client to make requests here, which fail for obvious reasons:

https://something.com/socket.io/...

So then I try to instantiate socket.io with the path option like so:

io.listen(server, { path: '/node.js/socket.io'} );

But the problem is that now the socket.io.js file is hosted here:

https://something.com/node.js/node.js/socket.io/socket.io.js

Is there a way to tell socket.io.js where to host the file socket.io.js but still use the given path?

What is the normal solution to this proxy_pass stuff with socket.io??

1

There are 1 best solutions below

2
On

Well different ways to solve your issue but I would use below one

location ~ /node.js/(.*) {
    rewrite "^/node.js/node.js/(.*)$" /node.js/$1 last;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-NginX-Proxy true;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "";

    add_header Cache-Control "public";

    proxy_set_header   X-Forwarded-Host   $host;
    proxy_set_header   X-Forwarded-Server $host;
    proxy_set_header   X-Forwarded-For    $proxy_add_x_forwarded_for;

    proxy_http_version 1.1;
    proxy_pass http://127.0.0.1:3000/$1$is_args$args;
}
location / {
    try_files $uri /index.php$is_args$args;
}