LoginSignup
6
4

More than 5 years have passed since last update.

HTTPSでの接続を有効にしたCloudFlareでHTTPからの接続をHTTPSに転送させるようにする

Posted at

CloudFlareを使うと証明書の取得にかかる費用がなく、HTTPSによる接続のサポートができます1

これはCloudFlareと自身のサーバーの間をHTTP接続にしても行えるのですが、そうした場合には自身のサーバー側にはHTTPによる接続として伝わるのでHTTPSでだけ接続を許可して、HTTPの場合にはHTTPSにリダイレクトをさせたい場合に少し手間が要ります。

CloudFlareはリクエスト時にX-HTTP-Forwarded-Protoヘッダーを送ってくれるのでそれを使うと良いでしょう。

/etc/nginx/sites-avalable/example.com.conf
server {
  listen 80;
  server_name example.com;

  # ...

  set $is_redirect "true";
  if ($scheme = "https") {
    set $is_redirect "false";
  }
  if ($http_x_forwarded_proto = "https") {
    set $is_redirect "false";
  }
  if ($is_redirect = "true") {
    rewrite . https://$host$uri permanent;
  }

  # ...
}

わたしは前述するような記述をNginxの設定ファイルに書き、解決させました。map ディレクティブを使うほうが綺麗に書けそうではあるのですが、取り急ぎで解決させられる簡単な方法で済ませました。

これはElastic Load Balancingでも同様のことができるので少し便利です。

結論

本当に安全に通信を行いたいのであれば、CDNやロードバランサーと自分のサーバーの間にインターネットを挟むのならばHTTPではなくHTTPSで接続を行うようにしましょう。

6
4
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
6
4