user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;

events {
    worker_connections 1024;
    use epoll;
    multi_accept on;
}

stream {
    log_format basic '$remote_addr [$time_local] '
                     '$protocol $status $bytes_sent $bytes_received '
                     '$session_time';
    access_log /var/log/nginx/stream.log basic;

    upstream mac_screen_sharing {
        server 192.168.1.122:5900;
    }

    server {
        listen 5901;
        proxy_pass mac_screen_sharing;
        proxy_connect_timeout 60s;
        proxy_timeout 300s;
    }
}

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    # 보안 헤더 (젤리핀 호환성 개선)
    add_header X-Frame-Options "SAMEORIGIN" always;
    # X-Content-Type-Options 제거 (젤리핀 JavaScript 파일 문제 해결)
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    
    server_tokens off;
    
    log_format security '$remote_addr - $remote_user [$time_local] '
                       '"$request" $status $body_bytes_sent '
                       '"$http_referer" "$http_user_agent" '
                       '$request_time $upstream_response_time';

    access_log /var/log/nginx/access.log security;

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    client_max_body_size 100M;

    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    # Rate Limiting (완화된 설정)
    limit_req_zone $binary_remote_addr zone=jellyfin:10m rate=50r/s;
    limit_req_zone $binary_remote_addr zone=komga:10m rate=30r/s;
    limit_req_zone $binary_remote_addr zone=webdav:10m rate=100r/s;
    limit_req_zone $binary_remote_addr zone=auth:10m rate=5r/m;
    limit_conn_zone $binary_remote_addr zone=perip:10m;
    limit_conn_zone $server_name zone=perserver:10m;
    
    # WebDAV 메소드 허용
    map $request_method $webdav_method {
        default 0;
        PROPFIND 1;
        PROPPATCH 1;
        MKCOL 1;
        COPY 1;
        MOVE 1;
        DELETE 1;
        LOCK 1;
        UNLOCK 1;
        OPTIONS 1;
    }
    
    

    upstream jellyfin_backend {
        server 192.168.1.122:8096;  # Mac Mini 직접 IP
        keepalive 32;
    }

    upstream komga_backend {
        server 192.168.1.122:25600;  # Komga 서버
        keepalive 16;
    }

    upstream webdav_backend {
        server 192.168.1.227:5006;  # 시놀로지 NAS WebDAV 서버 (HTTPS)
        keepalive 16;
    }

    upstream dsm_backend {
        server 192.168.1.227:5000;
        keepalive 16;
    }

    upstream document_backend {
        server 192.168.1.122:8181;
        keepalive 16;
    }

    upstream gitea_backend {
        server 192.168.1.227:10300;
        keepalive 16;
    }

    upstream vault_backend {
        server 192.168.1.227:8443;
        keepalive 16;
    }

    upstream news_backend {
        server 192.168.1.227:8080;
        keepalive 16;
    }




    # HTTP → HTTPS 리다이렉트
    server {
        listen 80;
        server_name jellyfin.hyungi.net komga.hyungi.net webdav.hyungi.net ds1525.hyungi.net document.hyungi.net git.hyungi.net vault.hyungi.net news.hyungi.net;
        
        # Let's Encrypt 인증 경로
        location /.well-known/acme-challenge/ {
            root /var/www/certbot;
        }
        
        # 나머지는 HTTPS로 리다이렉트
        location / {
            return 301 https://$server_name$request_uri;
        }
    }

    # HTTPS 서버 - Komga (우선순위 높음)
    server {
        listen 443 ssl;
        http2 on;
        server_name komga.hyungi.net;

        # SSL 설정 (Let's Encrypt 공인 인증서)
        ssl_certificate /etc/nginx/ssl/live/jellyfin.hyungi.net/fullchain.pem;
        ssl_certificate_key /etc/nginx/ssl/live/jellyfin.hyungi.net/privkey.pem;
        
        # SSL 보안 설정
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384;
        ssl_prefer_server_ciphers off;
        ssl_session_cache shared:SSL:10m;
        ssl_session_timeout 10m;

        # 보안 제한 (Komga용)
        limit_req zone=komga burst=50 nodelay;
        limit_conn perip 30;
        limit_conn perserver 100;

        # 로그인 페이지 특별 제한
        location ~ ^/(api/v1/users/me|login) {
            limit_req zone=auth burst=3 nodelay;
            proxy_pass http://komga_backend;
            include /etc/nginx/conf.d/security.conf;
        }

        # 메인 프록시 설정
        location / {
            proxy_pass http://komga_backend;
            include /etc/nginx/conf.d/security.conf;
        }

        # API 경로 (Komga REST API)
        location /api/ {
            proxy_pass http://komga_backend;
            include /etc/nginx/conf.d/security.conf;
        }

        # 보안: 숨겨야 할 경로들
        location ~ /\.ht {
            deny all;
        }
        
        location ~ /\. {
            deny all;
        }
    }

    # HTTPS 서버 - Jellyfin
    server {
        listen 443 ssl;
        http2 on;
        server_name jellyfin.hyungi.net;

        # SSL 설정 (Let's Encrypt 공인 인증서)
        ssl_certificate /etc/nginx/ssl/live/jellyfin.hyungi.net/fullchain.pem;
        ssl_certificate_key /etc/nginx/ssl/live/jellyfin.hyungi.net/privkey.pem;
        
        # SSL 보안 설정
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384;
        ssl_prefer_server_ciphers off;
        ssl_session_cache shared:SSL:10m;
        ssl_session_timeout 10m;

        # 보안 제한 (완화된 설정)
        limit_req zone=jellyfin burst=100 nodelay;
        limit_conn perip 50;
        limit_conn perserver 200;

        # 로그인 페이지 특별 제한
        location ~ ^/(Users/authenticatebyname|Users/AuthenticateByName) {
            limit_req zone=auth burst=3 nodelay;
            proxy_pass http://jellyfin_backend;
            include /etc/nginx/conf.d/security.conf;
        }

        # 메인 프록시 설정
        location / {
            proxy_pass http://jellyfin_backend;
            include /etc/nginx/conf.d/security.conf;
        }

        # 웹소켓 지원
        location /socket {
            proxy_pass http://jellyfin_backend;
            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;
        }

        # 보안: 숨겨야 할 경로들
        location ~ /\.ht {
            deny all;
        }
        
        location ~ /\. {
            deny all;
        }
    }

    # HTTPS 서버 - WebDAV (시놀로지 NAS)
    server {
        listen 443 ssl;
        # http2 on;  # WebDAV 호환성을 위해 HTTP/2 비활성화 (OmniFocus 등 일부 클라이언트 문제 방지)
        server_name webdav.hyungi.net;

        # SSL 설정 (WebDAV 전용 Let's Encrypt 인증서)
        ssl_certificate /etc/nginx/ssl/live/webdav.hyungi.net/fullchain.pem;
        ssl_certificate_key /etc/nginx/ssl/live/webdav.hyungi.net/privkey.pem;
        
        # SSL 보안 설정
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384;
        ssl_prefer_server_ciphers off;
        ssl_session_cache shared:SSL:10m;
        ssl_session_timeout 10m;

        # 보안 제한 (WebDAV용 - 파일 업로드 고려)
        limit_req zone=webdav burst=200 nodelay;
        limit_conn perip 50;
        limit_conn perserver 200;
        
        # WebDAV 전용 설정
        client_max_body_size 1G;  # 큰 파일 업로드 허용

        # 메인 프록시 설정 (WebDAV - 모든 경로)
        location / {
            proxy_pass https://webdav_backend;
            proxy_ssl_verify off;  # 내부망 인증서 검증 무시 (필요시)
            
            # 리다이렉트 포트 수정 (NAS가 5006을 붙여서 보내는 경우 443으로 수정)
            proxy_redirect https://webdav.hyungi.net:5006/ /;
            proxy_redirect https://$host:5006/ /;
            
            # 기본 프록시 헤더
            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_set_header X-Forwarded-Port 443;
            
            # WebDAV 전용 헤더
            proxy_set_header DAV "1";
            proxy_set_header Depth $http_depth;
            proxy_set_header Destination $http_destination;
            proxy_set_header Overwrite $http_overwrite;
            proxy_set_header Lock-Token $http_lock_token;
            proxy_set_header If $http_if;
            
            # WebDAV 메소드 및 타임아웃 설정
            proxy_request_buffering off;
            proxy_buffering off;
            proxy_read_timeout 600;
            proxy_send_timeout 600;
            proxy_connect_timeout 600;
            
            # HTTP 버전
            proxy_http_version 1.1;
            proxy_set_header Connection "";
        }

        # 보안: 숨겨야 할 경로들
        location ~ /\.ht {
            deny all;
        }
        
        location ~ /\. {
            deny all;
        }
    }

    # HTTPS 서버 - DSM (Synology)
    server {
        listen 443 ssl;
        http2 on;
        server_name ds1525.hyungi.net;

        ssl_certificate /etc/nginx/ssl/live/jellyfin.hyungi.net/fullchain.pem;
        ssl_certificate_key /etc/nginx/ssl/live/jellyfin.hyungi.net/privkey.pem;
        
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384;
        ssl_prefer_server_ciphers off;
        
        client_max_body_size 0;

        location / {
            proxy_pass http://dsm_backend;
            include /etc/nginx/conf.d/security.conf;
        }
    }

    # HTTPS 서버 - DevonThink (Document)
    server {
        listen 443 ssl;
        http2 on;
        server_name document.hyungi.net;

        ssl_certificate /etc/nginx/ssl/live/jellyfin.hyungi.net/fullchain.pem;
        ssl_certificate_key /etc/nginx/ssl/live/jellyfin.hyungi.net/privkey.pem;
        
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384;
        ssl_prefer_server_ciphers off;

        location / {
            proxy_pass http://document_backend;
            include /etc/nginx/conf.d/security.conf;
        }
    }

    # HTTPS 서버 - Gitea
    server {
        listen 443 ssl;
        http2 on;
        server_name git.hyungi.net;

        ssl_certificate /etc/nginx/ssl/live/jellyfin.hyungi.net/fullchain.pem;
        ssl_certificate_key /etc/nginx/ssl/live/jellyfin.hyungi.net/privkey.pem;
        
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384;
        ssl_prefer_server_ciphers off;
        
        client_max_body_size 512M;

        location / {
            proxy_pass http://gitea_backend;
            include /etc/nginx/conf.d/security.conf;
        }
    }

    # HTTPS 서버 - Vaultwarden
    server {
        listen 443 ssl;
        http2 on;
        server_name vault.hyungi.net;

        ssl_certificate /etc/nginx/ssl/live/jellyfin.hyungi.net/fullchain.pem;
        ssl_certificate_key /etc/nginx/ssl/live/jellyfin.hyungi.net/privkey.pem;
        
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384;
        ssl_prefer_server_ciphers off;

        location / {
            proxy_pass http://vault_backend;
            include /etc/nginx/conf.d/security.conf;
            
            # WebSocket support for Vaultwarden notifications
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
        }
    }

    # HTTPS 서버 - News (RSS)
    server {
        listen 443 ssl;
        http2 on;
        server_name news.hyungi.net;

        ssl_certificate /etc/nginx/ssl/live/jellyfin.hyungi.net/fullchain.pem;
        ssl_certificate_key /etc/nginx/ssl/live/jellyfin.hyungi.net/privkey.pem;
        
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384;
        ssl_prefer_server_ciphers off;

        location / {
            proxy_pass http://news_backend;
            include /etc/nginx/conf.d/security.conf;
        }
    }

}
