# Nginx Reverse Proxy for Matrix/Conduit
# Place in /etc/nginx/sites-available/matrix and symlink to sites-enabled

# HTTP → HTTPS redirect
server {
    listen 80;
    server_name matrix.fleet.tld;
    return 301 https://$server_name$request_uri;
}

# Main HTTPS server (client traffic)
server {
    listen 443 ssl http2;
    server_name matrix.fleet.tld;

    ssl_certificate /etc/letsencrypt/live/matrix.fleet.tld/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/matrix.fleet.tld/privkey.pem;

    # Security headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;

    # Matrix client-server API
    location /_matrix {
        proxy_pass http://127.0.0.1:6167;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        # WebSocket support (for sync)
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";

        # Timeouts for long-polling
        proxy_read_timeout 600s;
    }

    # Element web client (if self-hosting)
    location / {
        proxy_pass http://127.0.0.1:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

# Federation server (port 8448)
server {
    listen 8448 ssl http2;
    server_name matrix.fleet.tld;

    ssl_certificate /etc/letsencrypt/live/matrix.fleet.tld/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/matrix.fleet.tld/privkey.pem;

    location / {
        proxy_pass http://127.0.0.1:6167;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}
