为什么我的Nginx反向代理执行301重定向而不是代理?

问题描述:

我在Docker容器中有一个Nginx反向代理,它侦听端口3000并暴露给3002: docker run -p"3002:3000" ... .

I have an Nginx reverse proxy inside a docker container, which listens to port 3000 and is exposed to 3002: docker run -p "3002:3000" ....

这个想法是,这个反向代理将把/my-app 代理到我的笔记本电脑上运行的端口8080上的实例;和/my-app/api 到云实例(位于 https://my-domain 中).

The idea is that this reverse proxy will proxy /my-app to the instance running in my laptop on port 8080; and /my-app/api to the cloud instance, in https://my-domain.

这是配置:

upstream my-laptop {
  server host.docker.internal:8080; # this is a magic hostname for the laptop's IP address.
  keepalive 64;
}

upstream cloud {
  server my-domain.com:443;
  keepalive 64;
}

server {
    listen       3000;

    include ssl/ssl-certs.conf;
    include ssl/ssl-params.conf;

    location /my-app {
        proxy_pass http://my-laptop;
        proxy_set_header Host            $http_host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    location /my-app/api {
        proxy_pass https://cloud;
        proxy_set_header Host            $http_host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
    ...
}

问题是:

  1. 当我点击 https://localhost:3002/my-app 时,我收到对/my-app/的301响应(斜线).我不知道为什么.本地应用程序实例显示在浏览器中,所以我想我可以暂时让它滑动吗?
  2. 当我点击 https://localhost:3002/my-app/api/students 时,我收到对 https://cloud/my-app/api/的301响应学生.当然,这会导致CORS问题,并且端点不会返回数据.
  1. when I hit https://localhost:3002/my-app I get a 301 response to /my-app/ (trailing slash). I don't know why is that. The local app instance is shown in the browser, so I guess I can let it slide for the moment?
  2. when I hit https://localhost:3002/my-app/api/students, I get a 301 response to https://cloud/my-app/api/students. This causes CORS issues, of course, and the endpoint doesn't return data.

现在,我已经配置了几次反向代理,所以我完全没有看到什么错,这让我感到非常震惊,这不是我第一次.

Now, I have configured reverse proxies a couple of times, so I am completely shocked that I'm not seeing what's wrong, this is not my first time.

与其他应用程序的反向代理相比,我尝试过调整上游proxy_set_headers.我没主意了.

I have tried tweaking with the upstreams, the proxy_set_headers, compared with another reverse proxy that I have for a different app; I'm out of ideas.

我在做什么错了?

问题是我在云上游的 Host 标头,我有

The problem was my Host header in the cloud upstream, I had

proxy_set_header Host $http_host;

但这必须是

proxy_set_header Host my-domain.com;