Nginx使用http和https的upstream

13

我对nginx在http和https代理方面遇到了一些问题,在upstream块中。

upstream块:

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

当 http 80 出现问题(服务器宕机等)时,我希望重定向到 https 443。

这个代码块对我没有用。

location 块:

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

我该如何解决这个问题?


你应该更具体地说明你遇到了什么“不起作用”的问题。你遇到了哪些错误或行为,你想要发生什么? - AfroThundr
@dpnz 我有类似的用例,你找到合适的解决方案了吗? - Daniel Conde Marin
2个回答

2
这样做效果很好:为不同端口上的每个后端创建服务器配置部分,并在没有ssl的情况下将其内部转发到两个端口。
在这个例子中,您可以看到第一个服务器作为主服务器具有缓存内容(通过https可用),如果缓存内容不可用,则使用第二个服务器(通过http)。
(仅供参考,使用nginx 1.19.6)
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;
    }
}

1

试图猜测解决HTTP和HTTPS混合问题的方法,您可以在 location 块中尝试以下内容:

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;
    }
}

如果那不起作用,将 bypass 上游块分成 bypass1bypass2,并在相应的位置块中引用它们:

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;
    }
}

第三个选择是在端口80上引用它们两个,并确保第二个上游服务器将HTTP请求重定向到HTTPS。

不幸的是,“try_files”只接受单个命名位置,并且只能作为最后一个参数。 - Oleksandr Shmyrko

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接