繁体   English   中英

将 nginx 配置为 node.js 的反向代理有什么问题?

[英]what's wrong with this configuration for nginx as reverse proxy for node.js?

我有一个在 VPS 上运行的个人域。 我想将 nginx 设置为 node.js 应用程序的反向代理,但它不起作用。 谁能看看我的配置并告诉我我做错了什么?

假设我的域名是 example.com。 基本上,我想让它在我访问 node.example.com 时代理到 node.js 应用程序。 我还在 nginx 中设置了 blog.example.com 和 www.example.com。

这是我的反向代理的 nginx 配置(省略了 blog.example.com,www.example.com 设置):

server {
  listen 80;
  server_name node.example.com;

  access_log /srv/www/example.com/logs/node-access.log;
  error_log /srv/www/example.com/logs/node-error.log;

  location / {
      proxy_pass              http://example.com:3000/;
      proxy_redirect          off;
      proxy_set_header        Host            $host;
      proxy_set_header        X-Real-IP       $remote_addr;
      proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
      client_max_body_size    10m;
      client_body_buffer_size 128k;
      proxy_connect_timeout   90;
      proxy_send_timeout      90;
      proxy_read_timeout      90;
      proxy_buffers           32 4k;
  }
}

这是我的 node.js 应用程序:

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(3000, "example.com");

我重新启动了 nginx 服务器并运行了 node.js 应用程序。 但是,如果我访问 node.example.com,它会显示“node.example.com 不存在或不可用”。

我不确定我的配置有什么问题。 我也尝试了各种组合。

这些是我尝试过的配置:

proxy_pass in nginx           |   hostname in node.js app
http:// localhost:3000/        |   ---.listen(3000, "localhost")
http:// 127.0.0.1:3000/        |   ---.listen(3000, "127.0.0.1")
http:// node.example.com:3000/ |   ---.listen(3000, "node.example.com")

我还尝试了以下 nginx 配置:

upstream nodeapp {
  server 127.0.0.1:3000;
}

server {
   ...
   location / {
     proxy_pass     http:// nodeapp;
     ...
   }
   ...
}

它也不起作用。 我究竟做错了什么? 我在网上搜索了几个小时并尝试了各种方法,但它们似乎都不起作用。

如果有人可以帮助我,我将不胜感激。

谢谢!

在 nginx 配置( proxy_pass )中,您必须删除 (http://) 和(您的主机名)之间的 URL 中的空格:

你写了:

proxy_pass http:// nodeapp;

你必须写:

proxy_pass http://nodeapp ;

我尝试在我的服务器上添加空间 http:// .. 然后重新启动 nginx 但 nginx 失败了! 所以,我想这可能是你的 nginx 问题! 尝试删除此空间,我希望与您合作!

祝你好运!

.listen(3000, "example.com");代码.listen(3000, "example.com"); 在主机头中等待 example.com 所以尝试更改proxy_set_header Host $host;

到新的

proxy_set_header        Host            example.com;

如果您也想在 node.example.com 上运行您的 node.js 应用程序,那么在代理配置中,您需要在 127.0.0.1:3000 或 localhost:3000 上定义节点,而不是 example.com:3000

如果您需要使用 3000 作为端口在 example.com 上运行,那么最初您还需要为端口 80 定义 nginx 规则。 默认情况下,域映射到端口 80 和 443。休息一下,您可以在 node.js 启动文件中更改配置。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM