Redirecting to HTTPS with Node / Express on an Elastic Beanstalk

I am trying to get a site to force HTTPS (redirect with HTTP). We have HTTPS configured through AWS Elastic Beanstalk. The problem is that both HTTP and HTTPS can currently be used.

After reading a few posts, including this one , below is the code I came across. Unfortunately this does not work.

What am I missing?

import express from 'express';
import { join } from 'path';

const app = express();
const buildPath = join(`${__dirname}/../build`);
const enforceHTTPS = (req, res, next) => {
  if (req.headers['x-forwarded-proto'] === 'https') return next();
  else return res.redirect(301, join(`https://${req.hostname}${req.url}`));
};

app.use(express.static(buildPath));
app.use(enforceHTTPS);
app.get('*', (req, res) => res.sendFile(`${buildPath}/index.html`));
app.listen(process.env.PORT || 3000, () => console.log('Server running on port 3000!'));

export default app;
+4
source share
3 answers

, app.use - , .

, , IE/Edge, "https://" path.join( , , , IE ).

:

import express from 'express';
import { join } from 'path';

const app = express();
const buildPath = join(`${__dirname}/../build`);
const enforceHTTPS = (req, res, next) => {
  if (req.headers['x-forwarded-proto'] === 'https') return next();
  return res.redirect(301, `https://${join(req.hostname, req.url)}`);
};

app.use(enforceHTTPS);
app.use(express.static(buildPath));
app.get('*', (req, res) => res.sendFile(`${buildPath}/index.html`));
app.listen(process.env.PORT || 3000, () => console.log('Server running on port 3000!'));

export default app;
+1

, HTTPS 443. , . Express? HTTPS, , : http://expressjs.com/en/api.html HTTPS

var express = require('express');
var https = require('https');
var http = require('http');
var app = express();

http.createServer(app).listen(80);
https.createServer(options, app).listen(443);
0

When I used node.js as a proxy server in the past, the way we got unprotected connections to the proxy server for protection was as follows, modified according to your code:

const httpsPort = process.env.HTTPS_PORT;

app.use(function(req, res, next) {
    if (req.secure) {
        return next();
    }
    res.redirect(301, ['https://', req.hostname, ':', httpsPort, '/', req.url].join('');
}

Where httpsPort- whatever your port, your standard https connections. Where process.env.HTTPS_PORTwill get the environment variable for the https port (standard - 443). You can replace this with anything you want to get a port.

0
source

Source: https://habr.com/ru/post/1656653/


All Articles