I
I
ivandao2019-09-24 18:30:59
Node.js
ivandao, 2019-09-24 18:30:59

Redirect to https?

I want to redirect from http to https?
There is this code:

const PORT = 8889;
const PORT_HTTPS = 3443;

const fs = require('fs');
const express = require('express');
const app = express();
const https = require('https');


const privateKey  = fs.readFileSync( __dirname + '/cert/key.pem', 'utf8').toString();
const certificate = fs.readFileSync( __dirname + '/cert/server.crt', 'utf8').toString();

const credentials = {key: privateKey, cert: certificate, passphrase: ''};
const httpsServer = https.createServer(credentials, app);

app.use(express.static(__dirname + '/site'));

// Жалкая попытка редиректа
/* app.all('*', (req, res) => { 
    res.redirect(300, 'https://' + req.hostname + ':' + PORT_HTTPS + req.url) 
}); */

app.get('/', function(req, res) {...})
//...
app.post('/', function(req, res) {...})
//...

app.listen(PORT);
httpsServer.listen(PORT_HTTPS, () => console.log('HTTPS on ' + PORT_HTTPS));

What can be done about it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
SagePtr, 2019-09-24
@SagePtr

In addition, hang another server on port 80, all it will do is redirect to https. The easiest option:

const http = require('http');
http.createServer(function (req, res) {
    res.writeHead(301, { 'Location': 'https://' + req.headers.host + req.url });
    res.end();
}).listen(80);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question