nginx and node.js配合使用 helloworld

nginx是最好的反向代理服务器。

Node.js是。。。 好吧 ,不介绍了,猛击这里

现在小介绍下怎么用nginx和node.js配合使用。

先写个helloworld.js

[javascript] view plain copy
 
 print?
  1. var http = require('http');  
  2.   
  3.   
  4. http.createServer(function (request, response) {  
  5.     
  6.   response.writeHead(200, {'Content-Type': 'text/plain'});  
  7.   response.end('hello world ');  
  8. }).listen(8000);  
  9.   
  10.   
  11. console.log('Server running at http://127.0.0.1:8000/');  


然后用node helloworld.js指令开启,这样跑在本地的机子的nodejs的程序就算开起来了,占用的是8000端口,可自己修改。

接着,我们在nginx的vhost.conf里面写一个server

[python] view plain copy
 
 print?
  1. server {  
  2.     listen  80;  
  3.     server_name taqing.me www.taqing.me;  
  4.     location / {  
  5.     proxy_pass http://127.0.0.1:8000;  
  6.     }  
  7. }  


将网站域名设置好,然后端口设置为80,最后proxy_pass设置为http://127.0.0.1:8000,将所有从taqing.me:80的请求传递到nodejs程序去。

重启nginx

访问域名,就可以了看到helloworld了。

虽然node.js本身就可以做服务器是没错啦,比如welcome.js里面设置为80端口就可以了。

但是一个机子跑多个网站,其他网站又是用别的服务器,在80端口已经被占用的情况下,是可以用代理到别的端口来处理的。

原文地址:https://www.cnblogs.com/niejunchan/p/6505421.html