Https Power Requests in Express / Node

I have an Express.js server (v 2.5.8) (node ​​v0.6.12) running on port 3100. It is terminated by the Nginx front end, which proxies both HTTP and https requests to port 3100.

I want to force certain urls to https. Here is an example (the application is my express server):

app.get('/applyNow', ensureSec, secure.showApplication );

secureSec is a function that I am trying to check if the connection is completed by ssl:

function ensureSec(req, res, next) {
    if (req.session.ssl == true) { 
        return next(); 
    } else {
        req.session.ssl = true;
        res.redirect('https://' + url.parse(req.headers.referer).host +
        url.parse(req.url).pathname);
    }
}

Redirection works, but node (after timeout) gives an error message "Unable to GET / applyNow

What is the correct way to redirect to ssl?

+5
source share
7 answers

, nginx SSL HTTP, https- Express. nginx, , nginx , (.. https), - - , :

X-Forwarded-Proto nginx, https , https. nginx:

proxy_set_header X-Forwarded-Proto https;

Host:

proxy_set_header Host $http_host;

- ( , req.path, ):

function ensureSec(req, res, next) {
    if (req.headers['x-forwarded-proto'] == 'https') { 
        return next(); 
    } else {
        res.redirect('https://' + req.headers.host + req.path);
    }
}
+6

app. - . node.js-, 2 - app, http https. . :

SSL/https Express.js

. : / HTTPS node.js/express?

, req.session.ssl. true , TLS cleartext HTTP. . .

, http, https . http 80 https 443.

Cannot GET /applyNow, , - , ensureSec .

0

ssl nginx - node.js, .

http://nginx.org/en/docs/http/configuring_https_servers.html

node.js . 443 nginx - node.js.

0

, , , . HTTP- , EADDRINUSE.

0

: http://elias.kg/post/14971446990/force-ssl-with-express-js-on-heroku-nginx, Nginx "x-forwarded-proto":

function ensureSec(req, res, next){
    if (req.headers["x-forwarded-proto"] === "https"){
       return next();
    }
    res.redirect("https://" + req.headers.host + req.url);  
});
0

Nginx , () URL- http Nginx HTTPS Express. :

server {
  listen 12.34.56.78:80;
  server_name yourserver.com;

  location / {
      rewrite ^ https://$server_name$request_uri permanent;
  }
}

:

rewrite ^ https://ducklington.org$request_uri permanent;

Just configure your location according to the routes or rules you need to forward to https.

0
source

app.enable ('trusted proxy');

"Using Express behind a reverse proxy server, such as Varnish or Nginx, is trivial, but it requires configuration. By enabling the" trusted proxy "setting through app.enable (Express proxy), Express will know that it is sitting at the proxy server and that the X-Forwarded- * header fields can be trusted, which could otherwise be easily faked. "

Express for doco proxy

0
source

All Articles