1
5

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.

JSでhttpsにリダイレクトする

Last updated at Posted at 2018-08-23

こういうことはサーバーサイド側でやるべきだが、緊急の一次対応としてフロントエンド側で対応することが起こった。
もちろんサーバーサイドでの恒久対応は別途行うものとする。

問題のコード

「http → https にすればいいんだな」と思って文字列のreplace処理にこんなコードを書いた

var url = location.href

if(url.indexOf('http') >= 0) {
  // url文字列の書き換え
  var newUrl = url.replace('http', 'https');
  ...
}

「お、書き換わってる」成功だと思ったが、
数分後、問題に気づく。

「https」という文字列にも「http」が含まれているのだ。
なので、httpsのURLでアクセスした場合、if文の判定を通ってしまうため、
このままだと「https」 → 「httpss」 に置き換えられてしまう。

修正後

httpとhttpsをちゃんと区別するように一文字加えた。

var url = location.href

if(url.indexOf('http:') >= 0) { // 判定方法の修正
  // url文字列の書き換え
  var newUrl = url.replace('http:', 'https:'); // 書き換え方法の修正

  // リダイレクト
  location.replace(newUrl);
}

これでうまく行った。めでたしめでたし

まとめ

  • 書き換え後の文字列に、書き換え前の文字列がまるごと含まれている場合、判定・置換方法を注意しなければならない
1
5
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
1
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?