# ============================================================
# Nginx 反向代理配置 — OKR 绩效考核系统
# 用途: HTTPS 终端 + 安全头 + 反向代理到 Spring Boot
# 部署: cp okr-performance.conf /etc/nginx/sites-available/ && ln -s /etc/nginx/sites-enabled/
# ============================================================

# 上游服务 — Spring Boot 绑定 127.0.0.1:18080（不对外暴露）
upstream okr_backend {
    server 127.0.0.1:18080 fail_timeout=10s;
    keepalive 32;
}

# HTTP → HTTPS 强制跳转
server {
    listen 80;
    server_name okr.your-company.com;
    return 301 https://$host$request_uri;
}

# HTTPS 主服务
server {
    listen 443 ssl http2;
    server_name okr.your-company.com;

    # ===== TLS 证书（使用 certbot 自动管理） =====
    # 首次获取: certbot --nginx -d okr.your-company.com
    ssl_certificate     /etc/letsencrypt/live/okr.your-company.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/okr.your-company.com/privkey.pem;

    # ===== TLS 安全配置 =====
    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 on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;

    # HSTS — 强制浏览器使用 HTTPS（1年，含子域）
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

    # ===== 安全响应头 =====
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-Frame-Options "DENY" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;

    # CSP — 内容安全策略（根据实际需求调整）
    add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'" always;

    # ===== 日志（可选：采样以减少磁盘写入） =====
    access_log /var/log/nginx/okr-access.log combined buffer=16k;
    error_log  /var/log/nginx/okr-error.log warn;

    # 请求体大小限制（上传文件等）
    client_max_body_size 10m;

    # ===== 反向代理 =====
    location / {
        proxy_pass http://okr_backend;
        proxy_http_version 1.1;

        # WebSocket / 长连接支持
        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_connect_timeout 30s;
        proxy_read_timeout 60s;
        proxy_send_timeout 30s;

        # 缓冲设置
        proxy_buffering on;
        proxy_buffer_size 4k;
        proxy_buffers 8 16k;
    }

    # 屏蔽敏感路径
    location ~ /\. {
        deny all;
        return 404;
    }

    # 健康检查端点（可选）
    location /health {
        proxy_pass http://okr_backend/actuator/health;
        access_log off;
    }
}
