Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nginx upstream with http & https

I have some problem about nginx with http and https bypass, In upstream block

upstream block:

upstream bypass{
      server 192.168.99.1:80; #http
      server 192.168.99.2:443 backup; #https
}

When http 80 have a problem (server down, etc), I want to redirect to https 443,

This block does not work for me.

location block:

location / {
      proxy_pass https://bypass;
      proxy_redirect off;
}

How can I resolve this?

like image 809
dpnz Avatar asked Mar 16 '15 06:03

dpnz


2 Answers

This works well: Create server config section for each backend on different port and forward to both ports internally without ssl.

In this example, you can see how the first server acts as main server with cached content (available via https) and if cache content is not available, use the second server (via http).

(using nginx 1.19.6, just for reference)

upstream backends {
    server 127.0.0.1:8082;
    server 127.0.0.1:8081 backup;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;

    server_name example.com;

    # ssl certs etc here

    location / {
        proxy_pass http://backends;
        proxy_next_upstream error timeout http_404 http_403;
    }

    access_log  /var/log/nginx/access.log upstreamlog;
}

server {
    listen 8081;
    location / {
        add_header X-Cache MISS;
        proxy_pass http://server1;
        proxy_set_header Host server1;
    }
}


server {
    listen 8082;
    location / {
        add_header X-Cache HIT;
        proxy_pass https://server2;
        proxy_set_header Host server2;
    }
}
like image 93
Johan Avatar answered Sep 21 '22 23:09

Johan


Taking a shot in the dark. Assuming you were having issues mixing HTTP and HTTPS in the upstream, you could try this in the location block:

location {
    try_files @bypass-http @bypass-https =404;

    location @bypass-http {
        proxy_pass http://bypass;
        proxy_redirect off;
    }

    location @bypass-https {
        proxy_pass https://bypass;
        proxy_redirect off;
    }
}

And if that didn't work, split the bypass upstream block into bypass1 and bypass2 and reference them accordingly in their corresponding location blocks:

upstream bypass1{
      server 192.168.99.1:80; #http
}

upstream bypass2{
      server 192.168.99.2:443; #https
}

location {
    try_files @bypass-http @bypass-https =404;

    location @bypass-http {
        proxy_pass http://bypass1;
        proxy_redirect off;
    }

    location @bypass-https {
        proxy_pass https://bypass2;
        proxy_redirect off;
    }
}

A third option would be reference them both on port 80, and ensure the second upstream server redirects HTTP requests to HTTPS.

like image 42
AfroThundr Avatar answered Sep 23 '22 23:09

AfroThundr