Chittolina
Chittolina

Reputation: 235

NGINX: HTTP redirect to HTTPS not working with node

I'm trying to redirect all HTTP reqs to HTTPS reqs. My backend is with node. Here's my nginx config on conf.d/:

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. However if I use the HTTP protocol it does not work, ie, does not redirect to HTTPS.

Any suggestion?

Upvotes: 0

Views: 1175

Answers (1)

Fiid
Fiid

Reputation: 1840

I looked for a similar example and found this page: 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. 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

I'd also double check all the server_name entries in the config.

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. 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; just need to get the redirect to work properly.

Upvotes: 1

Related Questions