简体   繁体   English

NGINX:HTTP重定向到HTTPS不能与节点一起使用

[英]NGINX: HTTP redirect to HTTPS not working with node

I'm trying to redirect all HTTP reqs to HTTPS reqs. 我正在尝试将所有HTTP请求重定向到HTTPS请求。 My backend is with node. 我的后端是节点。 Here's my nginx config on conf.d/ : 这是我在conf.d /上的nginx配置:

upstream node {
server  127.0.0.1:8000;
}
server {
    listen      80;
    server_name mydomain.com;
    return 301  https://$server_name$request_uri;
}
server {
    listen 443 ssl;
    server_name mydomain.com;
    ssl on;
    gzip on;
    ssl_certificate /etc/letsencrypt/live/mydomain.com/cert.pem;
    ssl_certificate_key /etc/letsencrypt/live/mydomain.com/privkey.pem;
    ssl_stapling on;
    ssl_stapling_verify on;
    ssl_trusted_certificate /etc/letsencrypt/live/mydomain.com/fullchain.pem;
    ssl_session_timeout 5m;

location / {
    proxy_pass http://node;
    proxy_redirect off;
}

} }

Here's my node config: 这是我的节点配置:

// Calls config file to ExpressJS instance 
var app = require('./config/express')();

// Calls config file to MongoDB
require('./config/database')('mongodb://10.0.2.18/mydb');

http.createServer(app).listen(app.get('port'), function(){

console.log('HTTP listening on' + app.get('port'));

});

It's working when I explicitly use the HTTPS protocol. 当我明确使用HTTPS协议时,它就可以正常工作。 However if I use the HTTP protocol it does not work, ie, does not redirect to HTTPS. 但是,如果我使用HTTP协议,则该协议将不起作用,即不会重定向到HTTPS。

Any suggestion? 有什么建议吗?

I looked for a similar example and found this page: https://bjornjohansen.no/redirect-to-https-with-nginx 我寻找了类似的示例,并找到了以下页面: https : //bjornjohansen.no/redirect-to-https-with-nginx

The only meaningful difference I see is that on that on that page he's doing return 301 https://$host instead of $server_name . 我看到的唯一有意义的区别是,他在该页面上执行的操作是return 301 https://$host而不是$server_name This question seems to indicate that it might be better to use host: https://serverfault.com/questions/706438/what-is-the-difference-between-nginx-variables-host-http-host-and-server-na 这个问题似乎表明使用主机可能更好: https : //serverfault.com/questions/706438/what-is-the-difference-between-nginx-variables-host-http-host-and-server-呐

I'd also double check all the server_name entries in the config. 我还要仔细检查配置中的所有server_name条目。

You should be able to see the redirect by using a tool like Charles, wireshark, or maybe even the browser debugger too - so it ought to be possible to work out what's being sent back using that. 您应该可以使用Charles,wireshark甚至浏览器调试器之类的工具查看重定向,因此应该可以弄清楚使用该工具发送回的内容。 It may also be in the logfile. 它也可能在日志文件中。

If it works properly when you go directly to https:// that means that the https and the connection between nginx and node are working correctly; 如果直接进入https://时它可以正常工作,则表示https以及nginx和node之间的连接正常工作; just need to get the redirect to work properly. 只需要使重定向正常工作即可。

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

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