Nginx充当前端服务器,在这种情况下,它将代理请求发送到node.js服务器。因此,您需要为节点设置一个Nginx配置文件。
这是我在Ubuntu框中完成的操作:
yourdomain.com在
/etc/nginx/sites-available/以下位置创建文件:
vim /etc/nginx/sites-available/yourdomain.com
在其中您应该具有以下内容:
# the IP(s) on which your node server is running. I chose port 3000.upstream app_yourdomain { server 127.0.0.1:3000; keepalive 8;}# the nginx server instanceserver { listen 80; listen [::]:80; server_name yourdomain.com www.yourdomain.com; access_log /var/log/nginx/yourdomain.com.log; # pass the request to the node.js server with the correct headers # and much more can be added, see nginx config options 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; proxy_pass http://app_yourdomain/; proxy_redirect off; } }如果您还希望nginx(> = 1.3.13)也处理websocket请求,请在该
location /部分中添加以下行:
proxy_http_version 1.1;proxy_set_header Upgrade $http_upgrade;proxy_set_header Connection "upgrade";
完成此设置后,必须启用上面的配置文件中定义的站点:
cd /etc/nginx/sites-enabled/ ln -s /etc/nginx/sites-available/yourdomain.com yourdomain.com
在以下位置创建您的节点服务器应用程序并在以下位置
/var/www/yourdomain/app.js运行它
localhost:3000
var http = require('http');http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello Worldn');}).listen(3000, "127.0.0.1");console.log('Server running at http://127.0.0.1:3000/');测试语法错误:
nginx -t
重新启动nginx:
sudo /etc/init.d/nginx restart
最后启动节点服务器:
cd /var/www/yourdomain/ && node app.js
现在,您应该在yourdomain.com上看到“ Hello World”
关于启动节点服务器的最后一点说明:您应该对节点守护程序使用某种监视系统。有一个关于upstart和monit的很棒的教程。



