将 HTTP 请求代理到 nginx 中的 HTTPS 服务器

Eug*_*zov 4 ssl https proxy reverse-proxy nginx

我想设置一个 nginx 实例,它将从 /api 开始的 HTTP 请求代理到 HTTPS 服务器,但应该省略 /api URL 段。例如,实例应该侦听 localhost:9817。如果它收到对http://localhost:9817/api/auth的请求,它应该将其代理为https://api.com:8443/auth

这是我的 nginx 配置:

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,我在 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/"
Run Code Online (Sandbox Code Playgroud)

这个错误的原因是什么?我该如何修复它或根据需要设置代理?

小智 5

我遇到了同样的问题。我在这个stackoverflow 答案中找到了修复它的魔法动作

“尝试将 proxy_ssl_server_name on; 添加到您的 proxy_pass 块,看看是否有帮助”

它在我的 nginx.conf 中

   location / {
    proxy_pass https://$http_x_forwarded_to; 
}
Run Code Online (Sandbox Code Playgroud)

编辑后变成了

   location / {
    proxy_pass https://$http_x_forwarded_to; 
    proxy_ssl_server_name on;
}
Run Code Online (Sandbox Code Playgroud)

我可以再次享受生活