본문 바로가기

Develop/Web

[Node.js + Express] Redirect HTTP to HTTPS

 Node.js + Express 환경에서 HTTP 요청을 HTTPS로 redirect하는 미들웨어는 아래와 같이 구현할 수 있다.

 이 미들웨어는 request의 method와 무관하게 모든 요청을 다루지만, 특정 method(예: GET)만을 다루고 싶다면 5번째 줄의 .all() 대신 .get() 등을 사용하면 된다.

 

(ES6 기준)

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

// redirect HTTP to HTTPS
app.all('*', (req, res, next) =>
{
    let protocol = req.headers['x-forwarded-proto'] || req.protocol;

    if (protocol == 'https')
    {
        next();
    }
    else
    {
        let from = `${protocol}://${req.hostname}${req.url}`;
        let to = `https://${req.hostname}${req.url}`;

        // log and redirect
        console.log(`[${req.method}]: ${from} -> ${to}`);
        res.redirect(to);
    }
});

 

참고: https://expressjs.com/en/guide/routing.html