server {
    listen 80;
    server_name alexanderwhitestone.com 45.55.221.244;

    # Cookie-based auth gate — login once, cookie lasts 7 days
    location = /_auth {
        internal;
        proxy_pass http://127.0.0.1:9876;
        proxy_pass_request_body off;
        proxy_set_header Content-Length "";
        proxy_set_header X-Original-URI $request_uri;
        proxy_set_header Cookie $http_cookie;
        proxy_set_header Authorization $http_authorization;
    }

    location / {
        auth_request /_auth;
        # Forward the Set-Cookie from auth gate to the client
        auth_request_set $auth_cookie $upstream_http_set_cookie;
        add_header Set-Cookie $auth_cookie;

        proxy_pass http://127.0.0.1:3100;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host localhost;
        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-Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_read_timeout 86400;
    }

    # Return 401 with WWW-Authenticate when auth fails
    error_page 401 = @login;
    location @login {
        proxy_pass http://127.0.0.1:9876;
        proxy_set_header Authorization $http_authorization;
        proxy_set_header Cookie $http_cookie;
    }
}
