# Gitea Nginx 反向代理配置
# 由 deploy.sh 自动部署到 /etc/nginx/sites-available/gitea
# __GITEA_DOMAIN__ 会被脚本替换为实际域名

# HTTP → HTTPS 重定向
server {
    listen 80;
    listen [::]:80;
    server_name __GITEA_DOMAIN__;

    # Let's Encrypt 证书验证
    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }

    location / {
        return 301 https://$host$request_uri;
    }
}

# HTTPS 主站点
server {
    listen 443 ssl;
    listen [::]:443 ssl;
    http2 on;
    server_name __GITEA_DOMAIN__;

    # SSL 证书（Certbot 自动管理）
    ssl_certificate     /etc/letsencrypt/live/__GITEA_DOMAIN__/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/__GITEA_DOMAIN__/privkey.pem;

    # SSL 安全配置
    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;

    # HSTS（启用后浏览器会强制使用 HTTPS）
    add_header Strict-Transport-Security "max-age=63072000; 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;
    add_header Referrer-Policy strict-origin-when-cross-origin always;

    # Git LFS 和大仓库推送需要足够大的 body 限制
    client_max_body_size 512M;

    # 代理超时（大仓库 clone/push 可能较慢）
    proxy_connect_timeout 300;
    proxy_send_timeout    300;
    proxy_read_timeout    300;

    location / {
        proxy_pass http://127.0.0.1:3000;

        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 支持（Gitea 实时通知）
        proxy_http_version 1.1;
        proxy_set_header Upgrade    $http_upgrade;
        proxy_set_header Connection $http_connection;
    }

    # Git LFS 大文件upload需要特殊处理
    location ~ ^/.*\.git/info/lfs/ {
        proxy_pass http://127.0.0.1:3000;

        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;

        # LFS 上传可能很大
        client_max_body_size 4G;
        proxy_request_buffering off;
    }
}
