Nginx L4 Proxy Works with HTTPS but not with HTTP

I have the following configuration as L4 proxy over Nginx and everything works fine.

  stream {
 

    
    map $ssl_preread_server_name $name {
    hostnames;
    .ipchicken.com          $ssl_preread_server_name;
    .bbc.com                $ssl_preread_server_name;
    .bbc.co.uk              $ssl_preread_server_name;
    .bbci.co.uk             $ssl_preread_server_name;
    .neverssl.com           $ssl_preread_server_name;  #<-------
    
}


server {

    resolver 8.8.8.8;
    listen 443;
    ssl_preread on;
    proxy_connect_timeout 5s;
    proxy_pass $name:$server_port;
}

But when HTTP site is requested, like "http://neverssl.com/" Nginx is not responding. Any idea for this issue?


As far a I know ssl_preread directive works only with HTTPS protocol. I don't know how to get HTTP Host header value in the ngx_stream_core_module. You can try to use an additional server block in the http context like shown here:

http {
    ...
    map $http_host $proxy {
        hostnames;
        .neverssl.com    $http_host;
        ...
    }

    server {
        listen 80;
        resolver 8.8.8.8;
        location / {
            if ($proxy = '') { return 403; } # Return HTTP 403 Forbidden for unlisted domains
            proxy_set_header Host $proxy;
            proxy_redirect off;
            proxy_connect_timeout 5s;
            proxy_pass http://$proxy;
        }
    }
}

stream {
    ... # stream configuration for HTTPS port 443 here
}

There is no need to use $server_port variable at the stream server block, you are listening on the 443 port only, so you can just use proxy_pass $name:443;