# Ingress Setup & Redirects Guide

## 🎯 **Overview**

This guide covers advanced ingress configuration, redirects, and routing patterns. Building on your existing `Current_Ingress_Analysis.md`, this focuses on practical setup and common patterns.

---

## 📊 **Ingress Setup Process**

### **Step 1: Install Ingress Controller**

```bash
# Install nginx-ingress controller
kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.12.0/deploy/static/provider/cloud/deploy.yaml

# Verify installation
kubectl get pods -n ingress-nginx
kubectl get service ingress-nginx-controller -n ingress-nginx
```

### **Step 2: Configure DNS**

```bash
# Your actual Azure Load Balancer IP
# IP: 4.155.160.32 (prod-usw2-k8s-freeleaps-lb-fe-ip)

# Add DNS records:
# argo.mathmast.com → 4.155.160.32
# gitea.freeleaps.mathmast.com → 4.155.160.32
# magicleaps.mathmast.com → 4.155.160.32
# alpha.magicleaps.mathmast.com → 4.155.160.32
```

### **Step 3: Setup Cert-Manager**

```bash
# Install cert-manager
kubectl apply -f https://github.com/cert-manager/cert-manager/releases/download/v1.13.0/cert-manager.yaml

# Verify installation
kubectl get pods -n cert-manager
```

---

## 🔄 **Redirect Patterns**

### **1. HTTP to HTTPS Redirect**

```yaml
# ✅ BEST PRACTICE: Force HTTPS
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: secure-app-ingress
  annotations:
    nginx.ingress.kubernetes.io/ssl-redirect: "true"
    nginx.ingress.kubernetes.io/force-ssl-redirect: "true"
    cert-manager.io/cluster-issuer: "letsencrypt-prod"
spec:
  tls:
  - hosts:
    - myapp.example.com
    secretName: myapp-tls
  rules:
  - host: myapp.example.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: myapp-service
            port:
              number: 80
```

### **2. Path-Based Redirects**

```yaml
# Redirect /old to /new
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: redirect-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /new
    nginx.ingress.kubernetes.io/configuration-snippet: |
      location /old {
        return 301 /new;
      }
spec:
  rules:
  - host: myapp.example.com
    http:
      paths:
      - path: /old
        pathType: Prefix
        backend:
          service:
            name: myapp-service
            port:
              number: 80
```

### **3. Domain Redirects**

```yaml
# Redirect old domain to new domain
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: domain-redirect
  annotations:
    nginx.ingress.kubernetes.io/configuration-snippet: |
      if ($host = "old.example.com") {
        return 301 https://new.example.com$request_uri;
      }
spec:
  rules:
  - host: old.example.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: myapp-service
            port:
              number: 80
```

### **4. Subdomain Redirects**

```yaml
# Redirect www to non-www
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: www-redirect
  annotations:
    nginx.ingress.kubernetes.io/configuration-snippet: |
      if ($host = "www.example.com") {
        return 301 https://example.com$request_uri;
      }
spec:
  rules:
  - host: www.example.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: myapp-service
            port:
              number: 80
```

---

## 🎯 **Advanced Routing Patterns**

### **1. API Versioning**

```yaml
# Route different API versions
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: api-versioning
spec:
  rules:
  - host: api.example.com
    http:
      paths:
      - path: /v1
        pathType: Prefix
        backend:
          service:
            name: api-v1-service
            port:
              number: 8080
      - path: /v2
        pathType: Prefix
        backend:
          service:
            name: api-v2-service
            port:
              number: 8080
      - path: /
        pathType: Prefix
        backend:
          service:
            name: api-latest-service
            port:
              number: 8080
```

### **2. Blue-Green Deployment**

```yaml
# Route traffic between blue and green deployments
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: blue-green-routing
  annotations:
    nginx.ingress.kubernetes.io/configuration-snippet: |
      # Route 90% to blue, 10% to green
      set $upstream "";
      if ($request_uri ~ "^/blue") {
        set $upstream "blue-service:8080";
      }
      if ($request_uri ~ "^/green") {
        set $upstream "green-service:8080";
      }
      if ($upstream = "") {
        # Default routing logic
        set $random $remote_addr;
        if ($random ~ "^[0-9]$") {
          set $upstream "blue-service:8080";
        }
        if ($random ~ "^[a-f]$") {
          set $upstream "green-service:8080";
        }
      }
spec:
  rules:
  - host: myapp.example.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: blue-service
            port:
              number: 8080
```

### **3. Geographic Routing**

```yaml
# Route based on user location
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: geo-routing
  annotations:
    nginx.ingress.kubernetes.io/configuration-snippet: |
      # Route US users to US cluster, EU users to EU cluster
      set $upstream "";
      if ($http_x_forwarded_for ~ "^.*\.(us|ca)") {
        set $upstream "us-service:8080";
      }
      if ($http_x_forwarded_for ~ "^.*\.(eu|uk|de|fr)") {
        set $upstream "eu-service:8080";
      }
      if ($upstream = "") {
        set $upstream "default-service:8080";
      }
spec:
  rules:
  - host: myapp.example.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: default-service
            port:
              number: 8080
```

---

## 🔧 **Performance Optimizations**

### **1. Rate Limiting**

```yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: rate-limited-ingress
  annotations:
    nginx.ingress.kubernetes.io/rate-limit: "100"
    nginx.ingress.kubernetes.io/rate-limit-window: "1m"
    nginx.ingress.kubernetes.io/rate-limit-burst: "200"
spec:
  rules:
  - host: api.example.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: api-service
            port:
              number: 8080
```

### **2. Caching Headers**

```yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: cached-ingress
  annotations:
    nginx.ingress.kubernetes.io/configuration-snippet: |
      location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
      }
spec:
  rules:
  - host: myapp.example.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: myapp-service
            port:
              number: 80
```

### **3. Gzip Compression**

```yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: compressed-ingress
  annotations:
    nginx.ingress.kubernetes.io/enable-cors: "true"
    nginx.ingress.kubernetes.io/cors-allow-methods: "GET, POST, PUT, DELETE, OPTIONS"
    nginx.ingress.kubernetes.io/cors-allow-origin: "*"
    nginx.ingress.kubernetes.io/configuration-snippet: |
      gzip on;
      gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
spec:
  rules:
  - host: myapp.example.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: myapp-service
            port:
              number: 80
```

---

## 🛡️ **Security Patterns**

### **1. IP Whitelisting**

```yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: whitelisted-ingress
  annotations:
    nginx.ingress.kubernetes.io/whitelist-source-range: "10.0.0.0/8,192.168.0.0/16"
spec:
  rules:
  - host: internal.example.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: internal-service
            port:
              number: 8080
```

### **2. Basic Auth**

```yaml
# Create secret for basic auth
apiVersion: v1
kind: Secret
metadata:
  name: basic-auth-secret
type: Opaque
data:
  auth: <base64-encoded-htpasswd-file>
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: auth-ingress
  annotations:
    nginx.ingress.kubernetes.io/auth-type: basic
    nginx.ingress.kubernetes.io/auth-secret: basic-auth-secret
spec:
  rules:
  - host: protected.example.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: protected-service
            port:
              number: 8080
```

### **3. CORS Configuration**

```yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: cors-ingress
  annotations:
    nginx.ingress.kubernetes.io/enable-cors: "true"
    nginx.ingress.kubernetes.io/cors-allow-methods: "GET, POST, PUT, DELETE, OPTIONS"
    nginx.ingress.kubernetes.io/cors-allow-origin: "https://myapp.example.com"
    nginx.ingress.kubernetes.io/cors-allow-credentials: "true"
spec:
  rules:
  - host: api.example.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: api-service
            port:
              number: 8080
```

---

## 🔍 **Monitoring & Debugging**

### **1. Ingress Status Check**

```bash
# Check ingress status
kubectl get ingress --all-namespaces
kubectl describe ingress <ingress-name> -n <namespace>

# Check ingress controller logs
kubectl logs -n ingress-nginx deployment/ingress-nginx-controller

# Check certificate status
kubectl get certificates --all-namespaces
kubectl describe certificate <cert-name> -n <namespace>
```

### **2. Test Redirects**

```bash
# Test HTTP to HTTPS redirect
curl -I http://myapp.example.com
# Should return: 301 Moved Permanently

# Test domain redirect
curl -I http://old.example.com
# Should return: 301 Moved Permanently

# Test path redirect
curl -I http://myapp.example.com/old
# Should return: 301 Moved Permanently
```

### **3. Performance Testing**

```bash
# Test response times
curl -w "@curl-format.txt" -o /dev/null -s "https://myapp.example.com"

# Load testing
ab -n 1000 -c 10 https://myapp.example.com/

# SSL certificate check
openssl s_client -connect myapp.example.com:443 -servername myapp.example.com
```

---

## 📚 **Best Practices**

### **1. Always Use HTTPS**
```yaml
# ✅ DO: Force HTTPS redirect
nginx.ingress.kubernetes.io/force-ssl-redirect: "true"

# ❌ DON'T: Allow HTTP traffic
# nginx.ingress.kubernetes.io/ssl-redirect: "false"
```

### **2. Use Specific Path Types**
```yaml
# ✅ DO: Use specific path types
pathType: Prefix  # For /api/v1/*
pathType: Exact   # For exact matches
pathType: ImplementationSpecific  # For complex patterns

# ❌ DON'T: Use default path types without understanding
```

### **3. Implement Health Checks**
```yaml
# ✅ DO: Add health check endpoints
nginx.ingress.kubernetes.io/health-check-path: "/health"
nginx.ingress.kubernetes.io/health-check-interval: "30s"
```

### **4. Monitor Resource Usage**
```bash
# Monitor ingress controller resources
kubectl top pods -n ingress-nginx

# Monitor ingress metrics
kubectl get ingress --all-namespaces -o wide
```

---

## 🎯 **Your Current Setup Analysis**

Based on your `Current_Ingress_Analysis.md`, you have:

### **✅ What's Working Well:**
- **Nginx Ingress Controller**: Production-grade setup
- **Cert-Manager**: Automatic SSL certificates
- **DNS01 Challenge**: Reliable certificate validation
- **Custom Controller**: Automated ingress creation
- **Performance Optimizations**: Timeouts and body size limits

### **🔧 Potential Improvements:**
1. **Rate Limiting**: Add rate limiting for API endpoints
2. **Caching**: Implement caching for static assets
3. **Monitoring**: Add ingress metrics and alerts
4. **Backup Ingress**: Consider secondary ingress controller

---

**Last Updated**: September 3, 2025
**Version**: 1.0
**Maintainer**: Infrastructure Team
