在同一台机器上运行Node.js应用和PHP


Running Node.js app and PHP in same machine

我真的很困惑这是否可能?请帮助我,我有Node.js应用程序,说node_app,运行在X端口,和PHP应用程序,说my_app,运行在Apache的默认80端口。我只有一个域名。我的问题是,如果用户点击domain.com/my_app,它应该在80端口运行PHP应用程序。如果用户点击domain.com/node_app,它应该在X端口运行节点应用程序。另一个重要的约束是终端用户不应该在URL栏中看到任何端口号。

你可以在同一个主机上安装Node.JS和PHP,例如使用Nginx作为代理。

例如,使用Nginx,您可以创建两个虚拟主机:

  • 使用PHP的默认虚拟主机(FPM或非FPM),指向example .tld
  • 第二个虚拟主机到另一个节点。example .tld

第一个VH将是这样的(使用PHP-FPM):

server {
        listen   80; ## listen ipv4 port 80
        root /www;
        index index.php index.html index.htm;
        # Make site accessible from exemple.tld
        server_name exemple.tld;
        location / {
          try_files  $uri $uri/ /index.php;
        }
        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 and using HHVM or PHP
        #
        location ~ '.(hh|php)$ {
                try_files $uri =404;
                fastcgi_split_path_info ^(.+'.php)(/.+)$;
            fastcgi_keep_conn on;
                fastcgi_pass unix:/var/run/php5-fpm.sock;
                fastcgi_index index.php;
                include fastcgi_params;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        }
        location ~ /'.ht {
                deny all;
        }
}

第二个带有NodeJS的VH:

server {
    listen 80;
    server_name node.exemple.tld;
    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;
        access_log off;
        # Assuming that NodeJS listen to port 8888, change if it is listening to another port!
        proxy_pass http://127.0.0.1:8888/;
        proxy_redirect off;
        # Socket.IO Support if needed uncomment
        #proxy_http_version 1.1;
        #proxy_set_header Upgrade $http_upgrade;
        #proxy_set_header Connection "upgrade";
    }
    # IF YOU NEED TO PROXY A SOCKET ON A SPECIFIC DIRECTORY
    location /socket/ {
        # Assuming that the socket is listening the port 9090
            proxy_pass http://127.0.0.1:9090;
    }
}

如您所见,这是可能的,而且很容易做到!