'nginx ssl_preread_server_name shows wrong content

I'm having issues with my nginx configuration, we are using a stream in order to use SSL passthrough, however we plan on having multiple URLs pointed to this nginx and we are wanting to redirect to different load balancers depending on the address

Whats currently happening is..

Both site1.example.com and site2.example.com is showing site1.example.com content

And if site1.example.com load balancer stops working, both site1.example.com and site2.example end up showing site2.example.com content

/etc/nginx/nginx.conf

user  nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile on;
    keepalive_timeout 65;

    server {
        listen 80 default_server;
        listen [::]:80 default_server;
        server_name _;
        return 301 https://$host$request_uri;
    }
}

stream {
    log_format basic '$remote_addr [$time_local] '
                 '$protocol $status $bytes_sent $bytes_received '
                 '$session_time "$upstream_addr" '
                 '"$upstream_bytes_sent" "$upstream_bytes_received" "$upstream_connect_time"';

    access_log /var/log/nginx/access.log basic;
    error_log  /var/log/nginx/error.log;
   
    map $ssl_preread_server_name $name {
        site1.example.com site1_example_com;
        site2.example.com site2_example_com;
    }

    upstream site1_example_com {
        server site1.amazonaws.com:443 max_fails=3 fail_timeout=10s;
    }

    upstream site2_example_com {
        server site2.amazonaws.com:443 max_fails=3 fail_timeout=10s;
    }

    server {
        listen      443;
        proxy_pass  $name;
        ssl_preread on;
    }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source