Nginx充当前端服务器,在本例中,它将请求代理到 node .js服务器.因此,需要为 node 设置nginx配置文件.
这就是我在我的Ubuntu盒中所做的:
在/etc/nginx/sites-available/
处创建文件yourdomain.com
:
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 instance
server {
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;
}
}
If you want nginx (>= 1.3.13) to handle websocket requests as well, add the following lines in the location /
section:
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
创建 node 服务器应用程序,并在localhost:3000
运行
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).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
最后,启动 node 服务器:
cd /var/www/yourdomain/ && node app.js
现在你应该在你的域名上看到"Hello World".通用域名格式
关于启动 node 服务器的最后一个注意事项是:应该为 node 守护进程使用某种监视系统.有一个很棒的tutorial on node with upstart and monit.