Home > Software design >  HTTP nginx to HTTPS proxy_pass returns 504 BAD Gateway
HTTP nginx to HTTPS proxy_pass returns 504 BAD Gateway

Time:12-29

I'm trying to creating a proxy_pass to a https address (my nginx is running under 80 using plain HTTP protocol).

This is my declaration in conf file:

   location /viacep/ {
                  proxy_pass https://viacep.com.br/;
                  proxy_set_header X-Real-IP $remote_addr;
                  proxy_set_header Host $host;
                  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
       }

Well, the idea is when I enter in localhost/viacep/ws/09340400/json I got the following address resolution under the hood: https://viacep.com.br/ws/09340400/json. But I got the following error in error.log file:

2021/12/28 09:32:59 [error] 34664#0: *1 upstream prematurely closed connection while reading response header from upstream, client: 127.0.0.1, server: , request: "GET /viacep/ws/09540400/json HTTP/1.1", upstream: "https://165.227.126.241:443/ws/09540400/json", host: "localhost"

I imagine this error occurs because of the address resolved (https://165.227.126.241:443/ws/09540400/json), look it using IP instead of DNS.

Edit 1

I tried add proxy_ssl_server_name on; but same error.

CodePudding user response:

NGINX will allways resolve the DNS Name to an IP address.

The problem could be with the backend-servers SNI. Given there are multiple sites hosted on this server and the server supports SNI you should send the server name by using proxy_ssl_server_name on; in your NGINX configuration.

I have just configured that on my NGINX Version 1.20

server {
  listen 80;

  location / {
    proxy_pass https://viacep.com.br/;
    proxy_set_header Host viacep.com.br;
    proxy_set_header X-Forwarded-Proto https;
    proxy_ssl_server_name on;

  }
}

Make sure you are sending the right Host header. In your configuration you are sending localhost as Host to the upstream server. This will not work as you have noticed correctly.

  • Related