[KUBERNETES] HTTP to HTTPS Redirect dengan Envoy Gateway - fourslickz/notes GitHub Wiki

HTTP to HTTPS Redirect dengan Envoy Gateway

Problem

Jika menggunakan:

filters:
  - type: RequestRedirect

dan:

backendRefs:

dalam rule yang sama, maka Gateway API akan error:

RequestRedirect filter must not be used together with backendRefs

Selain itu, jika redirect diterapkan pada listener HTTPS juga, maka akan terjadi:

ERR_TOO_MANY_REDIRECTS

karena HTTPS akan redirect ke HTTPS lagi.


Solusi Benar

Pisahkan menjadi:

  1. HTTPRoute khusus redirect HTTP → HTTPS
  2. HTTPRoute khusus backend HTTPS

1. Hapus Route Lama

kubectl delete httproute nginx-route

2. Buat HTTP Redirect Route

4-http-redirect.yaml

apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: http-redirect

spec:
  hostnames:
    - aliensky.id

  parentRefs:
    - name: main-gateway
      sectionName: http

  rules:
    - filters:
        - type: RequestRedirect
          requestRedirect:
            scheme: https
            statusCode: 301

Apply

kubectl apply -f 4-http-redirect.yaml

3. Buat HTTPS Backend Route

5-https-backend.yaml

apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: https-backend

spec:
  hostnames:
    - aliensky.id

  parentRefs:
    - name: main-gateway
      sectionName: https

  rules:
    - matches:
        - path:
            type: PathPrefix
            value: /

      backendRefs:
        - name: nginx
          port: 80

Apply

kubectl apply -f 5-https-backend.yaml

4. Verifikasi

Cek HTTPRoute

kubectl get httproute

5. Testing

HTTP Redirect

curl -I http://aliensky.id

Harus:

301 Moved Permanently
Location: https://aliensky.id

HTTPS Backend

curl -I https://aliensky.id

Harus:

200 OK

Penjelasan sectionName

HTTP Listener

sectionName: http

Digunakan hanya untuk redirect.


HTTPS Listener

sectionName: https

Digunakan untuk backend aplikasi.


Arsitektur Final

HTTP
  ↓
301 Redirect
  ↓
HTTPS
  ↓
Envoy Gateway
  ↓
HTTPRoute
  ↓
Service
  ↓
Pod

Best Practice Production

Disarankan memisahkan file:

4-http-redirect.yaml
5-https-backend.yaml

agar:

  • lebih clean
  • mudah maintenance
  • mudah multi-domain
  • mudah GitOps

Verifikasi Gateway

kubectl get gateway

Harus:

PROGRAMMED=True

Verifikasi Certificate

kubectl get certificate

Harus:

READY=True

Verifikasi TLS Secret

kubectl get secret my-domain-tls

Hasil Akhir

Stack production sekarang memiliki:

  • K3s
  • Envoy Gateway
  • Gateway API
  • HTTPRoute
  • HTTPS
  • Let's Encrypt
  • cert-manager
  • Auto SSL renewal
  • HTTP → HTTPS redirect