Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proxy HTTP requests to an HTTPS server in nginx

I would like to set up an nginx instance which would proxy HTTP requests starting in /api to an HTTPS server, but the /api URL segment should be omitted out. For example, the instance should listen to localhost:9817. And if it receives a request to http://localhost:9817/api/auth, it should proxy it as https://api.com:8443/auth.

Here is my nginx config:

events {
    worker_connections  1024;
}

http {
    server {
        listen       9817;
        server_name  localhost;

        location /api {
            rewrite  ^/api(/.*) $1 break;
            proxy_pass https://api.com:8443;
            proxy_set_header Host $host;
            proxy_http_version 1.1;
        }

        location / {
            root  "D:/Project/dist";
            try_files $uri $uri/ /index.html;
        }
    }
}

However, I get the following error in error.log:

2020/01/16 17:54:22 [error] 420512#426216: *31 peer closed connection in SSL handshake (10054: An existing connection was forcibly closed by the remote host) while SSL handshaking to upstream, client: 127.0.0.1, server: localhost, request: "POST /api/auth HTTP/1.1", upstream: "https://16.53.35.38:8443/auth", host: "localhost:9817", referrer: "http://localhost:9817/"

What is the reason for this error? How can I fix it or set up proxying as I want to?

like image 865
Eugene Garbuzov Avatar asked Jan 16 '20 16:01

Eugene Garbuzov


1 Answers

I got same problem. I found magic action to fix it in this stackoverflow answer

"Try adding proxy_ssl_server_name on; to your proxy_pass block and see if it helps"

It was in my nginx.conf

   location / {
    proxy_pass https://$http_x_forwarded_to; 
}

After editing it became

   location / {
    proxy_pass https://$http_x_forwarded_to; 
    proxy_ssl_server_name on;
}

I can enjoy life again

like image 122
Костя Гришин Avatar answered Oct 07 '22 04:10

Костя Гришин