简体   繁体   中英

NodeJS/Express automatic detection of SSL over HTTP (HTTPS) explanation?

I have a server over HTTPS on NodeJS with Express.

When uploading a file, I have used the req.protocol directive in the controller to get either the HTTP or HTTPS "part" of the URL, so that I can save the file with the absolute URL. The problem is that without enabling the "trust proxy" setting of express ( http://expressjs.com/en/api.html#trust.proxy.options.table ), HTTPS doesn't get detected.

I thought this setting was used in the case of the actual redirect (when using the HTTP URL and the server doing the 301 redirect to HTTPS).

So this is more of an explanation question, rather than a solution one:

Why doesn't the HTTPS get detected when calling the URL through that?

trust proxy has nothing to do with 301 redirects.

That settings is important when running your node server behind a proxy :

  +----------HTTPS--------+---HTTP---+
  |                       |          |
client --> internet --> proxy --> node.js

It is typical that you have some sort of proxy between the internet and your node server; for example a CDN server, a load balancer, or simply an nginx instance or such. The HTTPS connection is established between the client and that proxy. The proxy cares about the necessary wrangling of the SSL certificate and encrypting the connection and doesn't burden your application server (node) with those details. It is then forwarding only the relevant details of the request via plain HTTP to your node server. Your server only sees the proxy as the origin of the request, not the client.

Since the node server didn't itself handle the HTTPS connection, how could it know whether the connection between the client and the proxy was HTTPS? It can't. The proxy needs to voluntarily forward that information too. It does so in the X-Forwarded-* HTTP headers. The information whether it was specifically HTTP or HTTPS is sent in the X-Forwarded-Proto header.

The thing is, those are just HTTP headers. Anyone can set those headers. The client itself could set those headers. That's why you need to explicitly opt into using those headers with the trust proxy setting, iif and when you know your app will be running behind a proxy which sets those headers. When you're not running behind a proxy but your node server is directly exposed to the internet, you must switch that setting off; otherwise anyone could set those headers, your server would obey those headers and be lead to use false information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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