12
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Node.js on HerokuでSSL(https)接続を強制する方法

Last updated at Posted at 2015-05-10

#httpで接続された場合にhttpsでredirectする

server.js
var express = require('express');
var app = express();

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

function forceHttps(req, res, next){
  if (!process.env.PORT) {
    return next();
  };

  if (req.headers['x-forwarded-proto'] && req.headers['x-forwarded-proto'] === "http") {
    res.redirect('https://' + req.headers.host + req.url);
  }else {
    return next();
  }
};

app.all('*', forceHttps);

app.get('/', function(req, res) {
  res.sendFile(__dirname + '/public/index1.html');
});

app.set('port', (process.env.PORT || 5000));

app.listen(app.get('port'), function() {
  console.log("Node app is running at localhost:" + app.get('port'))
})

##http接続の判定
Herokuを使っている場合はreq.secureを使っての判定ができないようです。
なのでreq.headers['x-forwarded-proto'] === "http"で判定しています。

##ローカル環境ではredirectされないようにする

  if (!process.env.PORT) {
    return next();
  };

##index.htmlを置くと判定を通らない・・・
index.htmlを置くとhttpアクセスの判定を通らずにファイルを落としてきてしまうためファイル名をindex1.htmlにしています。

12
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?