# 考培练系统 SaaS 超级管理后台
# 域名：admin.kpl.ireborn.com.cn

# HTTP 重定向到 HTTPS
server {
    listen 80;
    server_name admin.kpl.ireborn.com.cn;
    
    # Let's Encrypt 证书验证
    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }
    
    location / {
        return 301 https://$host$request_uri;
    }
}

# HTTPS
server {
    listen 443 ssl;
    http2 on;
    server_name admin.kpl.ireborn.com.cn;
    
    # SSL 证书
    ssl_certificate /etc/letsencrypt/live/admin.kpl.ireborn.com.cn/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/admin.kpl.ireborn.com.cn/privkey.pem;
    
    # SSL 配置
    ssl_session_timeout 1d;
    ssl_session_cache shared:AdminSSL:10m;
    ssl_session_tickets off;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    
    # 安全头
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
    
    # Docker DNS resolver
    resolver 127.0.0.11 valid=30s;
    
    # 动态 upstream 变量
    set $admin_frontend kaopeilian-admin-frontend;
    set $admin_backend kaopeilian-admin-backend;
    
    # API 路由 - 使用 rewrite 确保正确传递 URI
    location /api/ {
        rewrite ^/api/(.*)$ /api/$1 break;
        proxy_pass http://$admin_backend:8000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        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;
        proxy_cache_bypass $http_upgrade;
        proxy_read_timeout 300s;
        proxy_connect_timeout 75s;
        client_max_body_size 50M;
    }
    
    # 健康检查
    location = /health {
        proxy_pass http://$admin_backend:8000/health;
        proxy_set_header Host $host;
        access_log off;
    }
    
    # 前端静态资源
    location / {
        proxy_pass http://$admin_frontend:80;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        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;
        proxy_cache_bypass $http_upgrade;
        
        # HTML 不缓存
        add_header Cache-Control "no-cache, no-store, must-revalidate";
        add_header Pragma "no-cache";
        expires 0;
    }
}
