Nginx works as a front end server, which in this case proxies the requests to a node.js server.
(Nginx用作前端服务器,在这种情况下,它将代理请求发送到node.js服务器。)
Therefore you need to setup an nginx config file for node. (因此,您需要为节点设置一个nginx配置文件。)
This is what I have done in my Ubuntu box:
(这是我在Ubuntu框中完成的操作:)
Create the file yourdomain.com
at /etc/nginx/sites-available/
:
(在/etc/nginx/sites-available/
创建文件yourdomain.com
:)
vim /etc/nginx/sites-available/yourdomain.com
In it you should have something like:
(在其中您应该具有以下内容:)
# 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:
(如果您还希望nginx(> = 1.3.13)也处理websocket请求,请在location /
部分中添加以下行:)
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
Once you have this setup you must enable the site defined in the config file above:
(完成此设置后,必须启用上面的配置文件中定义的站点:)
cd /etc/nginx/sites-enabled/
ln -s /etc/nginx/sites-available/yourdomain.com yourdomain.com
Create your node server app at /var/www/yourdomain/app.js
and run it at localhost:3000
(在/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 World
');
}).listen(3000, "127.0.0.1");
console.log('Server running at http://127.0.0.1:3000/');
Test for syntax mistakes:
(测试语法错误:)
nginx -t
Restart nginx:
(重新启动nginx:)
sudo /etc/init.d/nginx restart
Lastly start the node server:
(最后启动节点服务器:)
cd /var/www/yourdomain/ && node app.js
Now you should see "Hello World" at yourdomain.com
(现在,您应该在yourdomain.com上看到“ Hello World”)
One last note with regards to starting the node server: you should use some kind of monitoring system for the node daemon.
(关于启动节点服务器的最后一点说明:您应该对节点守护程序使用某种监视系统。)
There is an awesome tutorial on node with upstart and monit . (有一个关于upstart和monit的很棒的教程 。)