如何配置nginx X-Forwarded-Port为原始请求端口

And*_*bbs 23 reverse-proxy nginx docker x-forwarded-for nginx-reverse-proxy

我在标准反向代理场景中使用 nginx,将所有请求传递/auth到另一台主机,但是我正在尝试使用非标准端口。

我的最终目标是将X-Forwarded-Port标头设置为请求进入的端口。

这是我在 nginx.conf 中的位置块:

location /auth/ {
    proxy_pass       http://otherhost:8090;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Forwarded-Host $host;
    proxy_set_header X-Forwarded-Port <VAR>;
}
Run Code Online (Sandbox Code Playgroud)

这个 nginx 运行在一个 docker 容器中,该容器被配置为将请求从 8085 转发到容器中的 80,这样 nginx 进程就可以监听 80:

0.0.0.0:8085->80/tcp

当我点击网址时:

http://localhost:8085/auth/

我正确重定向到http://otherhost:8090,但X-Forwarded-Port标题丢失或错误。

<VAR>原始块中,我尝试了以下操作:

  • $server_port - 这是 nginx 正在侦听的端口 (80),而不是请求端口。

  • $pass_port - 在我的设置中似乎为空,因此 nginx 删除了标头。

  • $http_port - 这是每个请求的随机端口。

  • $remote_port - 这是每个请求的随机端口。

可以在部署时将我的配置更改为硬编码到传入请求的已知端口,但理想情况下,我将能够更改前端端口,而无需对 nginx 配置进行任何更改。

我已经搜索了 nginx 变量列表,但找不到类似$request_port. 有什么方法可以实现我的意图吗?

pdi*_*aso 6

我发现的唯一解决方法是使用map规则从http_host变量中获取端口,例如

    map $http_host $port {
      default 80;
      "~^[^\:]+:(?<p>\d+)$" $p;
    }
Run Code Online (Sandbox Code Playgroud)


Dup*_*ngh 6

这是编写 Nginx conf 的一个粗略想法,但我相信这可以帮助您重定向

server {    
    listen 80;  
    server_name host.docker.internal;   

    # By default land on localhost:80 to root so in root we copied UI build to the ngnix html dir.
    # have a look to docker-compose uiapp service.
    location / {    
            root   /usr/share/nginx/html;   
            index  index.html index.htm;    
    }   

   # after location add filter, from which every endpoint starts with or comes in endpoint 
   # so that ngnix can capture the URL and reroute it.
   # like /backend/getUserInfo/<UserId> 
   # In above example /backend is that filter which will be captured by Ngnix and reroute the flow.
    location /backend { 
        proxy_set_header X-Forwarded-Host $host;    
        proxy_set_header X-Forwarded-Server $host;  
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        #proxy_pass http://<ContainerName>:<PortNumber>; 
        # In our case Container name is as we setup in docker-compose `beservice` and port 8080
        proxy_pass http://beservice:8080;   
    }   
}
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,您可以查看此项目

https://github.com/dupinder/NgnixDockerizedDevEnv


San*_*ann -3

奇怪的是,这个问题还没有答案,但答案是

proxy_set_header X-Forwarded-Port $server_port;
Run Code Online (Sandbox Code Playgroud)

  • 如果nginx前面有一个负载均衡器,它在端口8000上从客户端获取请求,并将其重定向到8100,并且nginx监听8100,那么$server_port是8100。但是作者需要原始端口请求 (8000) (5认同)