使用nginx运行node.js应用程序

我有一个运行在端口8443上的节点应用程序。我的nginx处理端口80和443上的web请求,并将用户redirect到8443。

这里是我的/etc/nginx/sites-enabled/defaultconfiguration:

 upstream my_upstream { server 127.0.0.1:8443; keepalive 64; } server { listen 80; server_name myapp.com; rewrite ^/(.*) https://myapp.com/$1 permanent; } server { listen 443 ssl; server_name 12.34.12.34 www.myapp.com myapp.com *.myapp.com; ssl_certificate /path/to/my/cert.crt; ssl_certificate_key /path/to/my/private.key // other ssl params location / { proxy_redirect off; proxy_pass https://my_upstream; // other params } } 

有了这个configuration我可以通过访问我的应用程序

 http(s)://myapp.com:8443 

只有当我添加下面的iptables

 iptables -t nat -A PREROUTING -p tcp --dport 443 -j REDIRECT --to-ports 8443 iptables -t nat -A OUTPUT -p tcp --dport 443 -o lo -j REDIRECT --to-port 8443 

我可以访问

 http(s)://myapp.com 

问题:

对于我来说,使用iptables从端口80redirect到443到8443似乎有点愚蠢。 有没有办法用nginx做到这一点(或者这是要走的路?)。

这种方法(在8443这样的非标准端口上应用)是一个好主意吗?

简单。 由于你的node.js是在8443端口上运行的,据我所知,你没有任何其他的服务监听其他端口的请求,你可以简单的在你的nginxconfiguration中做到这一点:

 server { # here comes the rest of your nginx configuration location / { proxy_pass http://127.0.0.1:8443; } } 

您不必使用任何iptables规则,也不必在您的nginxconfiguration中创build上游部分。 nginx可以(也应该)做所有的端口redirect开箱(正如任何反向代理一样)。

我可能是错的,但是你的应用程序在iptables规则之后开始工作的原因是因为你的客户端开始直接访问你的node.js服务器,因为端口redirect,这与我们使用Squid作为透明代理时类似。

这篇文章可以帮助你。 忽略它给Apache的事实:

祝你好运,最好的问候!

当你的上游运行在127.0.0.1时,在nginx和你的上游之间在127.0.0.1上执行encryption是有点毫无意义和浪费的。

如果有的话,使用iptablesredirect的解决scheme实际上比简单地将nginxjoin组合中更有效率,而不需要对上游进行任何更改。

但是我们必须问 – 如果你没有使用任何额外的nginx特性,你为什么要把它添加到混合首先?

正确的做法是在不使用https情况下运行上游,并使用nginx将http和httpsredirect到上游。 你目前的configuration不能工作的原因可能与一些configuration错误有关,从目前为止已经粘贴的代码片段中看不出来。