LoginSignup
3
4

More than 5 years have passed since last update.

Kubernetes Engineでhttpからhttpsにリダイレクトする

Last updated at Posted at 2018-11-25

2018年11月27日にいろいろ追記。。。

前提

  • Ingressを導入している(2018年11月27日追記)
  • GCPのロードバランサーにSSL証明書を設定している
  • nginxにはSSL証明書の設定をしていない

やること

Kubernetes Engineで動かすWEBサーバー(nginx)のコンテナでhttpをhttpsにリダイレクトさせる。すると、Ingressのコンテナのヘルスチェックに関する設定をしないと動かなくなるので、その設定方法を以下に。

nginxの設定

set $redirect 0;以下がヘルスチェックのための設定。ヘルスチェックのアクセスの場合はhttpsにリダイレクトしないようにしている。ヘルスチェックかどうかの判定はX_HEALTH_CHECKヘッダーで行う(好きなヘッダー名にしても良い)。

default.conf
server {
    listen      80;
    server_name localhost;

    set $redirect 0;

    if ($http_x_forwarded_proto = http) {
        set $recirect 1;
    }

    if ($http_x_health_check = on) {
        set $recirect 0;
    }

    if ($recirect = 1) {
        return 301 https://$host$request_uri;
    }
}

Deploymentの設定

spec.template.spec.containers[].livenessProbe.httpGet.httpHeadersX-Health-Check: onの設定をしている。これでヘルスチェックにリクエストヘッダーが付与される。

前述のnginxの設定でこのヘッダーを見てリダイレクトするかどうかを判定させている。なので、両方のヘッダー名を揃えておけば好きな名前に変更しても良い。

nginx-deployment.yaml
apiVersion: "extensions/v1beta1"
kind: "Deployment"
metadata:
  name: "nginx"
  namespace: "default"
  labels:
    app: "nginx"
spec:
  replicas: 1
  selector:
    matchLabels:
      app: "nginx"
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 0
  minReadySeconds: 5
  template:
    metadata:
      labels:
        app: "nginx"
    spec:
      containers:
      - name: "nginx"
        image: "<IMAGE>"
        livenessProbe:
          httpGet:
            scheme: HTTP
            path: /
            port: 80
            httpHeaders:
            - name: X-Health-Check
              value: "on"
          initialDelaySeconds: 5
          periodSeconds: 10

おしまい。

(以下2018年11月27日追記)

としていたが、上記のようなことをしなくてもよかった。

(新)nginxの設定

X_Fowarded_Protoヘッダーがある、かつ、https以外の場合はリダイレクトする。だけで良い。ヘルスチェックのリクエストにはX_Fowarded_Protoヘッダーがないため、この場合はhttpsにリダイレクトはしない。

これで、DeploymentのhttpHeaders設定はしなくて良い。

default.conf
server {
    listen      80;
    server_name localhost;

    if ($http_x_forwarded_proto) {
      set $redirect_to_https A;
    }

    if ($http_x_forwarded_proto != https) {
      set $redirect_to_https "${redirect_to_https}B";
    }

    if ($redirect_to_https = AB) {
      return 301 https://$host$request_uri;
    }
}

参考

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