# Nginx Provider Anleitung

**Umfassende Anleitung für den Nginx Open Source Provider in GAL (Gateway Abstraction Layer)**

## Inhaltsverzeichnis

1. [Übersicht](#übersicht)
2. [Schnellstart](#schnellstart)
3. [Installation und Setup](#installation-und-setup)
4. [Konfigurationsoptionen](#konfigurationsoptionen)
5. [Feature-Implementierungen](#feature-implementierungen)
6. [Provider-Vergleich](#provider-vergleich)
7. [Nginx-spezifische Details](#nginx-spezifische-details)
8. [OpenResty Integration](#openresty-integration-optional)
9. [Best Practices](#best-practices)
10. [Troubleshooting](#troubleshooting)

---

## Übersicht

Nginx ist der **#1 Web Server weltweit** mit über 30% Marktanteil. Als Open-Source Reverse Proxy und Load Balancer ist Nginx bekannt für:

- ✅ **Hohe Performance** - Extrem ressourcenschonend
- ✅ **Stabilität** - Bewährt in Production seit 2004
- ✅ **Einfachheit** - Klare, lesbare Konfiguration
- ✅ **Flexibilität** - Vielseitig einsetzbar
- ✅ **Community** - Riesige Community und Dokumentation

### Warum Nginx mit GAL?

GAL abstrahiert die Nginx-Konfiguration und ermöglicht:
- 🔄 **Provider-Unabhängigkeit** - Gleiche Config für alle Gateways
- 📝 **YAML statt nginx.conf** - Einfachere Konfiguration
- 🚀 **Schneller Start** - Weniger Boilerplate
- 🔍 **Validierung** - Automatische Checks vor Deployment

### Unterstützte Features

| Feature | Nginx Open Source | Nginx Plus | GAL Support |
|---------|-------------------|------------|-------------|
| **Reverse Proxy** | ✅ | ✅ | ✅ Full |
| **Load Balancing** | ✅ | ✅ | ✅ Full |
| **Rate Limiting** | ✅ | ✅ | ✅ Full |
| **Basic Auth** | ✅ | ✅ | ✅ Full |
| **Header Manipulation** | ✅ | ✅ | ✅ Full |
| **CORS** | ✅ | ✅ | ✅ Full |
| **Passive Health Checks** | ✅ | ✅ | ✅ Full |
| **Active Health Checks** | ❌ | ✅ | ⚠️ Plus only |
| **JWT Authentication** | ⚠️ Lua | ✅ | ⚠️ OpenResty |
| **Dynamic Config** | ❌ | ✅ | ⚠️ Plus only |
| **API Key Auth** | ⚠️ Lua | ✅ | ⚠️ OpenResty |
| **Circuit Breaker** | ⚠️ Lua | ✅ | ⚠️ Limited |

**Legende:**
- ✅ **Full** - Vollständig unterstützt
- ⚠️ **Limited** - Eingeschränkt oder benötigt Erweiterungen
- ❌ **Not Supported** - Nicht verfügbar

---

## Schnellstart

### 1. Basis-Konfiguration (Reverse Proxy)

Einfachster Nginx Reverse Proxy:

```yaml
version: "1.0"
provider: nginx

global:
  port: 80

services:
  - name: api_service
    type: rest
    protocol: http
    host: backend.internal
    port: 8080

    routes:
      - path_prefix: /api
        methods: [GET, POST, PUT, DELETE]
```

**Generieren:**
```bash
gal generate config.yaml --provider nginx > nginx.conf
```

**Resultat:**
```nginx
# Nginx Configuration Generated by GAL

events {
    worker_connections 1024;
}

http {
    # Basic Settings
    include /etc/nginx/mime.types;
    default_type application/octet-stream;
    sendfile on;
    keepalive_timeout 65;

    # Server for api_service
    server {
        listen 80;
        server_name api_service.local;

        # Route: /api
        location /api {
            # Proxy to backend
            proxy_pass http://backend.internal:8080;
            proxy_http_version 1.1;
            proxy_set_header Connection "";
            proxy_connect_timeout 5s;
            proxy_send_timeout 60s;
            proxy_read_timeout 60s;
        }
    }
}
```

### 2. Load Balancing

Mehrere Backend-Server mit Load Balancing:

```yaml
version: "1.0"
provider: nginx

services:
  - name: api_service
    type: rest
    protocol: http
    upstream:
      targets:
        - host: api-1.internal
          port: 8080
          weight: 2        # Erhält 2x mehr Traffic
        - host: api-2.internal
          port: 8080
          weight: 1
      load_balancer:
        algorithm: least_conn  # Least Connections

    routes:
      - path_prefix: /api
```

**Generiert:**
```nginx
upstream upstream_api_service {
    least_conn;
    server api-1.internal:8080 weight=2;
    server api-2.internal:8080;
    keepalive 32;
}

server {
    listen 80;
    location /api {
        proxy_pass http://upstream_api_service;
    }
}
```

### 3. Rate Limiting + Basic Auth

API-Schutz mit Rate Limiting und Authentication:

```yaml
version: "1.0"
provider: nginx

services:
  - name: protected_api
    type: rest
    protocol: http
    host: api.internal
    port: 8080

    routes:
      - path_prefix: /api
        rate_limit:
          enabled: true
          requests_per_second: 100
          burst: 200
          response_status: 429

        authentication:
          enabled: true
          type: basic
          basic_auth:
            users:
              admin: "password"
              user: "secret"
            realm: "Protected API"
```

**Generiert:**
```nginx
http {
    # Rate Limiting Zones
    limit_req_zone $binary_remote_addr zone=protected_api_route_0_ratelimit:10m rate=100r/s;

    server {
        location /api {
            # Rate Limiting: 100 req/s, burst 200
            limit_req zone=protected_api_route_0_ratelimit burst=200 nodelay;
            limit_req_status 429;

            # Basic Authentication
            auth_basic "Protected API";
            auth_basic_user_file /etc/nginx/.htpasswd;

            proxy_pass http://api.internal:8080;
        }
    }
}
```

**Wichtig:** Erstelle `.htpasswd` Datei:
```bash
htpasswd -c /etc/nginx/.htpasswd admin
htpasswd /etc/nginx/.htpasswd user
```

---

## Installation und Setup

### Nginx Installation

**Ubuntu/Debian:**
```bash
sudo apt update
sudo apt install nginx
```

**CentOS/RHEL:**
```bash
sudo yum install nginx
```

**macOS:**
```bash
brew install nginx
```

### GAL CLI Installation

```bash
pip install gal-gateway
```

### Nginx Config Deployment

1. **Config generieren:**
```bash
gal generate gateway.yaml --provider nginx > nginx.conf
```

2. **Config testen:**
```bash
nginx -t -c nginx.conf
```

3. **Config deployen:**
```bash
sudo cp nginx.conf /etc/nginx/nginx.conf
sudo nginx -s reload
```

Oder für lokales Testing:
```bash
nginx -c $(pwd)/nginx.conf
```

---

## Konfigurationsoptionen

### Global Configuration

```yaml
global:
  port: 80           # Listen Port (default: 10000)
  host: 0.0.0.0      # Listen Address
  admin_port: 9901   # Nicht verwendet bei Nginx
  timeout: "30s"     # Request Timeout
```

### Upstream Configuration

```yaml
upstream:
  targets:           # Liste von Backend-Servern
    - host: server1.internal
      port: 8080
      weight: 2      # Load Balancing Gewicht (default: 1)

  health_check:
    passive:         # Passive Health Checks
      enabled: true
      max_failures: 3
      unhealthy_status_codes: [500, 502, 503, 504]

  load_balancer:
    algorithm: round_robin  # round_robin, least_conn, ip_hash, weighted
```

**Load Balancing Algorithmen:**

| Algorithm | Beschreibung | Nginx Direktive | Use Case |
|-----------|--------------|-----------------|----------|
| `round_robin` | Gleichmäßige Verteilung (default) | - | Standard |
| `least_conn` | Zu Server mit wenigsten Verbindungen | `least_conn;` | Ungleiche Requests |
| `ip_hash` | Basierend auf Client-IP (Sticky) | `ip_hash;` | Session Persistence |
| `weighted` | Gewichtete Verteilung | `weight=N` | Heterogene Server |

### Route Configuration

```yaml
routes:
  - path_prefix: /api           # Routing Pfad
    methods: [GET, POST]        # Erlaubte HTTP Methoden

    rate_limit:                 # Rate Limiting
      enabled: true
      requests_per_second: 100
      burst: 200
      key_type: ip_address      # ip_address, header
      key_header: X-API-Key     # Falls key_type=header
      response_status: 429

    authentication:             # Authentication
      enabled: true
      type: basic               # basic, api_key, jwt
      basic_auth:
        users:
          admin: password
        realm: "Protected"

    headers:                    # Header Manipulation
      request_add:
        X-Request-ID: "{{uuid}}"
        X-Gateway: "GAL"
      response_add:
        X-Frame-Options: "DENY"
      response_remove:
        - X-Powered-By

    cors:                       # CORS
      enabled: true
      allowed_origins: ["https://app.example.com"]
      allowed_methods: [GET, POST]
      allowed_headers: [Content-Type, Authorization]
      allow_credentials: true
      max_age: 86400
```

---

## Feature-Implementierungen

### 1. Load Balancing

#### Round Robin (Default)

Gleichmäßige Verteilung über alle Server:

```yaml
upstream:
  targets:
    - host: server1
      port: 8080
    - host: server2
      port: 8080
  load_balancer:
    algorithm: round_robin
```

**Nginx Config:**
```nginx
upstream upstream_service {
    server server1:8080;
    server server2:8080;
}
```

#### Least Connections

Bevorzugt Server mit wenigsten aktiven Verbindungen:

```yaml
load_balancer:
  algorithm: least_conn
```

**Nginx Config:**
```nginx
upstream upstream_service {
    least_conn;
    server server1:8080;
    server server2:8080;
}
```

**Use Case:** Backend-Server mit stark variierenden Request-Dauern.

#### IP Hash (Session Persistence)

Client-IP bestimmt Backend-Server (Sticky Sessions):

```yaml
load_balancer:
  algorithm: ip_hash
```

**Nginx Config:**
```nginx
upstream upstream_service {
    ip_hash;
    server server1:8080;
    server server2:8080;
}
```

**Use Case:** Stateful Applications, Session Persistence.

#### Weighted

Server mit unterschiedlichen Kapazitäten:

```yaml
upstream:
  targets:
    - host: powerful-server
      port: 8080
      weight: 3
    - host: small-server
      port: 8080
      weight: 1
```

**Nginx Config:**
```nginx
upstream upstream_service {
    server powerful-server:8080 weight=3;
    server small-server:8080;
}
```

**Verteilung:** 75% powerful-server, 25% small-server.

### 2. Passive Health Checks

Nginx überwacht Backend-Health basierend auf echtem Traffic:

```yaml
upstream:
  targets:
    - host: backend1
      port: 8080
  health_check:
    passive:
      enabled: true
      max_failures: 3           # Nach 3 Fehlern → unhealthy
```

**Nginx Config:**
```nginx
upstream upstream_service {
    server backend1:8080 max_fails=3 fail_timeout=30s;
}
```

**Funktionsweise:**
- Bei 3 aufeinanderfolgenden Fehlern wird Server als "down" markiert
- Nach 30 Sekunden wird Server wieder getestet
- Fehler = 5xx Status Codes oder Timeouts

⚠️ **Limitation:** Kann Server nicht proaktiv prüfen (kein Active HC ohne Plus).

### 3. Rate Limiting

IP-basiertes Rate Limiting:

```yaml
rate_limit:
  enabled: true
  requests_per_second: 100
  burst: 200
  key_type: ip_address
  response_status: 429
```

**Nginx Config:**
```nginx
http {
    limit_req_zone $binary_remote_addr zone=api_ratelimit:10m rate=100r/s;

    server {
        location /api {
            limit_req zone=api_ratelimit burst=200 nodelay;
            limit_req_status 429;
        }
    }
}
```

**Erklärung:**
- **Zone:** 10m = ~160.000 IP-Adressen
- **Rate:** 100 Requests/Sekunde
- **Burst:** Bis zu 200 Requests in Spitzen
- **nodelay:** Keine künstliche Verzögerung

#### Header-basiertes Rate Limiting

Limitierung pro API-Key:

```yaml
rate_limit:
  enabled: true
  requests_per_second: 50
  key_type: header
  key_header: X-API-Key
```

**Nginx Config:**
```nginx
limit_req_zone $http_x_api_key zone=api_ratelimit:10m rate=50r/s;
```

### 4. Authentication

#### Basic Authentication

Einfache Username/Password Auth:

```yaml
authentication:
  enabled: true
  type: basic
  basic_auth:
    users:
      admin: "password"
    realm: "Protected API"
```

**Nginx Config:**
```nginx
location /api {
    auth_basic "Protected API";
    auth_basic_user_file /etc/nginx/.htpasswd;
}
```

**Setup:**
```bash
# .htpasswd erstellen
htpasswd -c /etc/nginx/.htpasswd admin
# Weitere User hinzufügen
htpasswd /etc/nginx/.htpasswd user2
```

#### API Key Authentication

⚠️ **Benötigt Lua/OpenResty** oder externe Authentication.

```yaml
authentication:
  type: api_key
  api_key:
    keys: ["key_123abc"]
    key_name: X-API-Key
    in_location: header
```

**Nginx Config (Kommentar):**
```nginx
# API Key authentication not natively supported
# Requires Lua or external authentication
```

**Alternative:** Nginx Plus mit `auth_request` Modul oder OpenResty.

#### JWT Authentication

⚠️ **Benötigt OpenResty/Lua** (siehe [OpenResty Integration](#openresty-integration-optional)).

```yaml
authentication:
  type: jwt
  jwt:
    issuer: "https://auth.example.com"
    audience: "api"
    jwks_uri: "https://auth.example.com/.well-known/jwks.json"
```

### 5. Header Manipulation

#### Request Headers

```yaml
headers:
  request_add:
    X-Request-ID: "{{uuid}}"     # $request_id
    X-Gateway: "GAL"
    X-Timestamp: "{{now}}"        # $time_iso8601
  request_set:
    User-Agent: "GAL-Gateway/1.0"
  request_remove:
    - X-Internal-Token
```

**Nginx Config:**
```nginx
location /api {
    # Request Headers
    proxy_set_header X-Request-ID $request_id;
    proxy_set_header X-Gateway 'GAL';
    proxy_set_header X-Timestamp $time_iso8601;
    proxy_set_header User-Agent 'GAL-Gateway/1.0';
    proxy_set_header X-Internal-Token '';
}
```

**Template-Variablen:**
- `{{uuid}}` → `$request_id`
- `{{now}}`, `{{timestamp}}` → `$time_iso8601`

#### Response Headers

```yaml
headers:
  response_add:
    X-Frame-Options: "DENY"
    X-Content-Type-Options: "nosniff"
  response_set:
    Server: "GAL-Gateway"
  response_remove:
    - X-Powered-By
```

**Nginx Config:**
```nginx
location /api {
    # Response Headers
    add_header X-Frame-Options 'DENY' always;
    add_header X-Content-Type-Options 'nosniff' always;
    add_header Server 'GAL-Gateway' always;

    # Note: Response header removal requires ngx_headers_more module
    # more_clear_headers 'X-Powered-By';
}
```

⚠️ **Response Header Removal** benötigt `ngx_headers_more` Modul.

### 6. CORS

Cross-Origin Resource Sharing für SPAs:

```yaml
cors:
  enabled: true
  allowed_origins:
    - "https://app.example.com"
    - "https://www.example.com"
  allowed_methods: [GET, POST, PUT, DELETE, OPTIONS]
  allowed_headers: [Content-Type, Authorization, X-API-Key]
  expose_headers: [X-Request-ID, X-RateLimit-Remaining]
  allow_credentials: true
  max_age: 86400  # 24 hours
```

**Nginx Config:**
```nginx
location /api {
    # CORS Configuration
    add_header 'Access-Control-Allow-Origin' 'https://app.example.com' always;
    add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
    add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization, X-API-Key' always;
    add_header 'Access-Control-Expose-Headers' 'X-Request-ID, X-RateLimit-Remaining' always;
    add_header 'Access-Control-Allow-Credentials' 'true' always;
    add_header 'Access-Control-Max-Age' '86400' always;

    # Handle preflight requests
    if ($request_method = 'OPTIONS') {
        return 204;
    }
}
```

**Wichtig:** `always` Flag stellt sicher, dass Headers auch bei Errors gesetzt werden.

---

## Provider-Vergleich

### Nginx vs. Andere Gateways

| Feature | Nginx | Kong | APISIX | Traefik | Envoy |
|---------|-------|------|--------|---------|-------|
| **Performance** | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
| **Memory Footprint** | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐ |
| **Lernkurve** | ⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐ |
| **Community** | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ |
| **Static Content** | ⭐⭐⭐⭐⭐ | ⭐⭐ | ⭐⭐ | ⭐⭐⭐ | ⭐⭐ |
| **Dynamic Config** | ⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ |
| **Plugin Ecosystem** | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ |
| **JWT Native** | ❌ | ✅ | ✅ | ⚠️ | ✅ |
| **Active HC** | ❌ | ✅ | ✅ | ✅ | ✅ |
| **Complexity** | Low | Medium | Medium | Low | High |

### Wann Nginx nutzen?

**✅ Ideal für:**
- Static Content Serving + API Gateway Hybrid
- Einfache Reverse Proxy Setups
- Minimaler Memory Footprint erforderlich
- Bewährte, stabile Lösung gewünscht
- Team hat Nginx-Erfahrung
- On-Premises Deployment

**⚠️ Weniger geeignet für:**
- Hochdynamische Konfigurationen (ohne Plus)
- Native JWT Validation erforderlich
- Umfangreiche Plugin-Infrastruktur gewünscht
- Active Health Checks ohne Plus

---

## Nginx-spezifische Details

### nginx.conf Struktur

GAL generiert folgende Struktur:

```nginx
events {
    worker_connections 1024;
}

http {
    # Basic Settings
    include /etc/nginx/mime.types;
    default_type application/octet-stream;
    sendfile on;
    keepalive_timeout 65;

    # Logging
    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    # Rate Limiting Zones (global)
    limit_req_zone ...

    # Upstream Blocks
    upstream upstream_service1 { ... }
    upstream upstream_service2 { ... }

    # Server Blocks
    server {
        listen 80;
        server_name service1.local;

        # Location Blocks
        location /api { ... }
        location /v2 { ... }
    }

    server {
        listen 80;
        server_name service2.local;
        ...
    }
}
```

### Worker Configuration

Für Production solltest du Worker-Prozesse anpassen:

```nginx
# Am Anfang der nginx.conf (vor events)
user www-data;
worker_processes auto;  # Anzahl CPU Cores
pid /run/nginx.pid;

events {
    worker_connections 4096;  # Pro Worker
    multi_accept on;
}
```

### SSL/TLS Termination

Füge SSL manuell hinzu (noch nicht von GAL unterstützt):

```nginx
server {
    listen 443 ssl http2;
    server_name api.example.com;

    ssl_certificate /etc/nginx/ssl/cert.pem;
    ssl_certificate_key /etc/nginx/ssl/key.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;

    location /api {
        proxy_pass http://upstream_service;
    }
}
```

### Logging Configuration

Custom Access Log Format:

```nginx
http {
    log_format gal_format '$remote_addr - $remote_user [$time_local] '
                         '"$request" $status $body_bytes_sent '
                         '"$http_referer" "$http_user_agent" '
                         'rt=$request_time uct="$upstream_connect_time" '
                         'uht="$upstream_header_time" urt="$upstream_response_time"';

    access_log /var/log/nginx/access.log gal_format;
}
```

---

## OpenResty Integration (Optional)

OpenResty erweitert Nginx mit LuaJIT für dynamische Features.

### Installation

```bash
# Ubuntu/Debian
sudo apt install openresty

# macOS
brew install openresty/brew/openresty
```

### JWT Authentication mit OpenResty

Installiere `lua-resty-jwt`:

```bash
opm get SkyLothar/lua-resty-jwt
```

**Nginx Config (manuell):**
```nginx
location /api {
    access_by_lua_block {
        local jwt = require "resty.jwt"
        local validators = require "resty.jwt-validators"

        local auth_header = ngx.var.http_Authorization
        if not auth_header then
            ngx.status = 401
            ngx.say("Missing Authorization header")
            return ngx.exit(401)
        end

        local token = string.gsub(auth_header, "^Bearer ", "")

        local jwt_obj = jwt:verify("YOUR_SECRET_KEY", token, {
            iss = validators.equals("https://auth.example.com"),
            aud = validators.equals("api"),
        })

        if not jwt_obj["verified"] then
            ngx.status = 401
            ngx.say("Invalid token: " .. jwt_obj.reason)
            return ngx.exit(401)
        end
    }

    proxy_pass http://backend;
}
```

⚠️ **Hinweis:** GAL generiert Kommentare für JWT, die du durch OpenResty-Code ersetzen musst.

---

## Best Practices

### 1. Worker Configuration

```nginx
worker_processes auto;  # 1 pro CPU Core
worker_rlimit_nofile 65535;

events {
    worker_connections 4096;
    use epoll;  # Linux
    multi_accept on;
}
```

### 2. Connection Pooling

```nginx
upstream backend {
    server backend1:8080;
    keepalive 32;  # Keep 32 idle connections
    keepalive_requests 100;
    keepalive_timeout 60s;
}
```

### 3. Timeouts

```nginx
proxy_connect_timeout 5s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
client_body_timeout 30s;
client_header_timeout 30s;
```

### 4. Buffer Sizes

```nginx
client_body_buffer_size 128k;
client_max_body_size 10m;
proxy_buffer_size 4k;
proxy_buffers 8 4k;
proxy_busy_buffers_size 8k;
```

### 5. Security Headers

```nginx
add_header X-Frame-Options "DENY" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
```

### 6. Rate Limiting Best Practices

- **Zone Size:** 10m = ~160k IPs, 100m = ~1.6M IPs
- **Burst:** 2x `requests_per_second` als Faustregel
- **nodelay:** Verwende immer `nodelay` für API Gateways
- **Key Selection:** Wähle zwischen IP, Header, JWT Claim basierend auf Use Case

### 7. Health Checks

- **max_fails:** 3-5 für Production
- **fail_timeout:** 10s-30s (Balance zwischen Fehlertoleranz und Recovery)
- **Monitoring:** Nutze Nginx Stub Status oder Prometheus Exporter

---

## Troubleshooting

### Problem: "Too many open files"

**Symptom:**
```
nginx: [emerg] socket() failed (24: Too many open files)
```

**Lösung:**
```nginx
worker_rlimit_nofile 65535;
```

Oder System Limit erhöhen:
```bash
ulimit -n 65535
```

### Problem: Rate Limiting funktioniert nicht

**Check:**
1. Zone definiert in `http` Block?
```nginx
http {
    limit_req_zone $binary_remote_addr zone=myzone:10m rate=100r/s;
}
```

2. Zone referenziert in `location`?
```nginx
location /api {
    limit_req zone=myzone burst=200 nodelay;
}
```

3. Log-Datei prüfen:
```bash
tail -f /var/log/nginx/error.log | grep limit_req
```

### Problem: Upstream Server wird nicht erreicht

**Debug:**
```nginx
error_log /var/log/nginx/error.log debug;
```

**Check:**
1. Server erreichbar?
```bash
curl http://backend:8080/health
```

2. DNS korrekt?
```bash
nslookup backend.internal
```

3. Firewall Rules?
```bash
sudo iptables -L -n
```

### Problem: CORS funktioniert nicht

**Häufiger Fehler:** `always` Flag vergessen.

**Richtig:**
```nginx
add_header 'Access-Control-Allow-Origin' '*' always;
```

**Falsch:**
```nginx
add_header 'Access-Control-Allow-Origin' '*';  # Nur bei 200 OK
```

### Problem: Config Reload schlägt fehl

**Test vor Reload:**
```bash
nginx -t -c /etc/nginx/nginx.conf
```

**Häufige Fehler:**
- Fehlende Semikolons
- Unbalanced Brackets
- Ungültige Direktiven
- Falsche Pfade

### Problem: 502 Bad Gateway

**Ursachen:**
1. Backend offline → Check `max_fails`
2. Timeout zu kurz → Erhöhe `proxy_read_timeout`
3. Buffer zu klein → Erhöhe `proxy_buffer_size`

**Debug:**
```nginx
error_log /var/log/nginx/error.log debug;
```

Suche nach:
```
upstream timed out
no live upstreams
```

---

## Zusammenfassung

### Stärken von Nginx

✅ **Performance** - Extrem schnell und ressourcenschonend
✅ **Stabilität** - Bewährt in Production
✅ **Einfachheit** - Klare, lesbare Konfiguration
✅ **Community** - Riesige Community, viele Tutorials
✅ **Static Content** - Perfekt für Hybrid Workloads

### Einschränkungen

❌ **Active Health Checks** - Nur in Nginx Plus
❌ **JWT** - Benötigt OpenResty/Lua
❌ **Dynamic Config** - Reload erforderlich
⚠️ **Response Header Removal** - Benötigt ngx_headers_more Modul

### Empfehlung

Nutze Nginx mit GAL wenn:
- 🚀 Performance und Effizienz kritisch sind
- 📦 Static Content + API Gateway benötigt wird
- 🔧 Einfache, stabile Lösung gewünscht ist
- 💰 Keine Lizenzkosten anfallen sollen

Nutze andere Gateways wenn:
- 🔑 Native JWT Validation erforderlich ist
- 🔄 Dynamische Configuration ohne Reload benötigt wird
- 🎯 Active Health Checks ohne Plus erforderlich sind

---

## Weitere Ressourcen

- **Nginx Offizielle Docs:** https://nginx.org/en/docs/
- **OpenResty Docs:** https://openresty.org/en/
- **GAL GitHub:** https://github.com/pt9912/x-gal
- **PyPI Package:** https://pypi.org/project/gal-gateway/

**Bei Fragen oder Problemen:** https://github.com/pt9912/x-gal/issues
