user2779686
user2779686

Reputation: 23

how to use node.js and php on the same port

I've installed node.js, socket.io, and express.js on port 12234 and that works very nice. But now I want to use php on an page on that port (12234) but I don't know how I can do that. Has anybody a solution?

sorry for my bad english, I'm Netherlands and not really good in english.

Upvotes: 2

Views: 2279

Answers (2)

hexacyanide
hexacyanide

Reputation: 91669

You can't run two applications on the same port. The easiest thing to do is proxy HTTP requests to PHP, running on another port, and proxy other requests to Socket.IO, running on another port.

Here's an example using http-proxy. Do note that this won't work for things like flashsockets and XHR long polling.

var httpProxy = require('http-proxy')

var server = httpProxy.createServer(function (req, res, proxy) {
  proxy.proxyRequest(req, res, {
    host: 'localhost',
    port: // whatever port PHP is running on
  });
})

server.on('upgrade', function (req, socket, head) {
  server.proxy.proxyWebSocketRequest(req, socket, head, {
    host: 'localhost',
    port: // whatever port Socket.IO is running on
  });
});

server.listen(80);

Alternatively, you could route your Express routes to PHP. If PHP was running on port 8080 for example:

app.get('/', function(req, res) {
  // send a HTTP get request
  http.get({hostname: 'localhost', port: 8080, path:'/', function(res2) {
    // pipe the response stream
    res2.pipe(res);
  }).on('error', function(err) {
    console.log("Got error: " + err.message);
  });
});

Upvotes: 6

Ben Fortune
Ben Fortune

Reputation: 32127

You can have node.js running as an upstream through nginx. Providing you're using nginx and php5-fpm.

upstream node {
    server 127.0.0.1:8080;
}

location / {
    proxy_pass  http://node;
    proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
    proxy_redirect off;
    proxy_buffering off;
    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_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "Upgrade";
}

location ~ \.php$ {
    index index.php;
    root   /var/www;
    fastcgi_pass   127.0.0.1:9000;
    fastcgi_index  index.php;
    include        fastcgi_params;
    fastcgi_param  SCRIPT_FILENAME  /var/www/$fastcgi_script_name;
}

Upvotes: 1

Related Questions