Skip to content

Instantly share code, notes, and snippets.

@hareeqi
Last active October 2, 2023 04:54
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hareeqi/dcc0d409db57668294a7f0d8970aa1e4 to your computer and use it in GitHub Desktop.
Save hareeqi/dcc0d409db57668294a7f0d8970aa1e4 to your computer and use it in GitHub Desktop.
Redirect HTTP to HTTPS nodeJs (http2https.js)
// Make sure to run the code using sudo as port 80 needs sudo access
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(301,{Location: `https://${req.headers.host}${req.url}`});
res.end();
});
server.listen(80);
console.log(`http2https ==> 80:443`);
@loretoparisi
Copy link

A more generic solution can be achieved with a simple middleware

app.use(function(request, response, next) {
    if (process.env.NODE_ENV != 'development' && !request.secure) {
       return response.redirect("https://" + request.headers.host + request.url);
    }
    next();
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment