lukeed / polka

A micro web server so fast, it'll make you dance! :dancers:
MIT License
5.42k stars 174 forks source link

Forcing SSL #158

Closed shipcommit closed 3 years ago

shipcommit commented 3 years ago

How would you suggest forcing HTTPS, by re-directing from HTTP?

lukeed commented 3 years ago

Hey, this: https://github.com/lukeed/polka/tree/master/examples/with-https

It only accepts HTTPS connections. That said, you should be doing this at the DNS/proxy layer whenever possible, leaving the Node.js layer to just be application logic.

lukeed commented 3 years ago

If you really want to, you can stand up a second server on :80 and forcibly redirect to the https protocol of the same URL. Again, I don't recommend this as it's not the right solution layer IMO

polka().use((req, res) => {
  res.writeHead(301, {
    'Location': `https://example.com${req.url}`
  });
  res.end('redirecting you');
}).listen(80)
shipcommit commented 3 years ago

I had a further look at Heroku's documentation, and they recommend re-directs to be done at the application level: https://help.heroku.com/J2R1S4T8/can-heroku-force-an-application-to-use-ssl-tls

I've tried your last recommendation, but it causes my application to crash, by running a second server after the first one.

polka().use((req, res) => {
  res.writeHead(301, {
    'Location': `https://${req.url}`
  });
  res.end('redirecting you');
}).listen(80)

This seems to be a very Heroku specific thing, because for other hosting platforms I do get recommendations on setting up a reverse proxy with either nginx or Caddy.

Considering the above, how would your recommend I re-direct all http requests to https?

lukeed commented 3 years ago

I mentioned two servers and wrote 80 specifically. 80 would be handling all http requests and 443 would be handling at https requests.

I do not know how you'd set that up on heroku

Additionally, I think there's a http request header that specifies the current protocol. I don't know for sure & wouldn't remember its name, but you can try that route too -- meaning if the protocol is not https then you do a redirect.