19

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.

1 Answer 1

39

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I agree. This prevent hair-pulling incidents whilst copy-pasting configs around between location blocks. You don't want an http ending up in an https server location block, or vice versa.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.