如何配置 nginx 使其与 Express 一起使用?

Mar*_*son 14 nginx reverse-proxy http-headers node.js

我正在尝试配置 nginx,以便它proxy_pass向我的节点应用程序发出请求。关于 StackOverflow 的问题得到了很多赞成:https ://stackoverflow.com/questions/5009324/node-js-nginx-and-now ,我正在使用那里的配置。

(但由于问题是关于服务器配置,它应该在 ServerFault 上)

这是nginx配置:

server {
  listen 80;
  listen [::]:80;

  root /var/www/services.stefanow.net/public_html;
  index index.html index.htm;
  server_name services.stefanow.net;

  location / {
    try_files $uri $uri/ =404;
  }

  location /test-express {
    proxy_pass    http://127.0.0.1:3002;
  }    

  location /test-http {
    proxy_pass    http://127.0.0.1:3003;
  }
}
Run Code Online (Sandbox Code Playgroud)

使用普通节点:

var http = require('http');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(3003, '127.0.0.1');

console.log('Server running at http://127.0.0.1:3003/');
Run Code Online (Sandbox Code Playgroud)

有用! 检查:http : //services.stefanow.net/test-http

使用快递:

var express = require('express');
var app = express(); //

app.get('/', function(req, res) {
  res.redirect('/index.html');
});

app.get('/index.html', function(req, res) {
  res.send("blah blah index.html");
});

app.listen(3002, "127.0.0.1");
console.log('Server running at http://127.0.0.1:3002/');
Run Code Online (Sandbox Code Playgroud)

它不起作用:( 见:http : //services.stefanow.net/test-express


我知道有些事情正在发生。

a) test-express 没有运行 在此处输入图片说明

b) text-express 正在运行

在此处输入图片说明

(我可以确认它是通过命令行运行的,而 ssh 在服务器上)

root@stefanow:~# service nginx restart
 * Restarting nginx nginx                                                                                  [ OK ]

root@stefanow:~# curl localhost:3002
Moved Temporarily. Redirecting to /index.html

root@stefanow:~# curl localhost:3002/index.html
blah blah index.html
Run Code Online (Sandbox Code Playgroud)

我尝试按照此处所述设置标头:http : //www.nginxtips.com/how-to-setup-nginx-as-proxy-for-nodejs/(仍然不起作用)

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;
Run Code Online (Sandbox Code Playgroud)

我也尝试用 'localhost' 替换 '127.0.0.1',反之亦然


请指教。我很确定我错过了一些明显的细节,我想了解更多。谢谢你。

Ale*_*Ten 25

您表示配置为服务路径/index.html,但您需要/test-express/index.html. 配置 express 以提供服务/test-express/index.html或使 nginx/test-exress从代理请求中剥离。后者就像在location和 中添加尾部斜杠一样简单proxy_pass

location /test-express/ {
  proxy_pass    http://127.0.0.1:3002/;
}
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅http://nginx.org/r/proxy_pass

  • **Q:**“我很确定我错过了一些明显的细节”**A:**“就像添加尾部斜杠一样简单”(谢谢,我真的被卡住了) (3认同)