upstream api_server {
    # fail_timeout=0 means we always retry an upstream even if it failed
    # to return a good HTTP response

    # for UNIX domain socket setups
    #server unix:/tmp/gunicorn.sock fail_timeout=0;

    # for a TCP configuration
    # TODO: use gunicorn to manage multiple processes
    server api_server:8080 fail_timeout=0;
}

upstream web_server {
    server web_server:3000 fail_timeout=0;
}

server {
    listen 80;
    server_name ${DOMAIN};

    client_max_body_size 5G;    # Maximum upload size    

    # Match both /api/* and /openapi.json in a single rule
    location ~ ^/(api|openapi.json)(/.*)?$ {
        # Rewrite /api prefixed matched paths
        rewrite ^/api(/.*)$ $1 break;

        # misc headers
        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_set_header Host $host;

        # need to use 1.1 to support chunked transfers
        proxy_http_version 1.1;
        proxy_buffering off;

        # we don't want nginx trying to do something clever with
        # redirects, we set the Host: header above already.
        proxy_redirect off;
        proxy_pass http://api_server;
    }

    location / {
        # misc headers
        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_set_header Host $host;

        proxy_http_version 1.1;

        # we don't want nginx trying to do something clever with
        # redirects, we set the Host: header above already.
        proxy_redirect off;
        proxy_pass http://web_server;
    }
}
