NGINX proxy_pass same protocol (http/https)

nginx

I have a section in my NGINX config file that uses proxy_pass to redirect API traffic to upstream servers. I have the locations in one server block that serves both http and https requests:

server {
    listen 80;
    listen [::]:80;
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name mysite.local;    # Valid TLD in production

I then have location blocks to define my API gateways:

    location /api/v1/json {
        # Various proxy config directives
        proxy_pass http://upstream;

My question is: would it be possible to drop http:// and pass requests to my upstream servers depending on the protocol without splitting my server block? Something like HTML/JavaScript //mysite.local requests.

Best Answer

You could use the $scheme variable:

location /api/v1/json {
    # Various proxy config directives
    proxy_pass $scheme://your-host
}

From the docs:

$scheme
request scheme, "http" or "https"

Which would then use the same protocol as the original request.