我在标准反向代理方案中使用nginx,将所有对/auth
的请求传递到另一台主机,但是我试图使用非标准端口。
我的最终目标是将X-Forwarded-Port
header 设置为发出请求的端口。
这是我在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>; }
此nginx在docker容器中运行,该容器配置为将请求从8085转发到容器中的80,这样nginx进程正在侦听80:
0.0.0.0:8085->80/tcp
当我点击网址时:
我已正确重定向到
http://otherhost:8090
,但是X-Forwarded-Port
header 丢失或错误。在原始块中有
<VAR>
的地方,我尝试了以下操作:$server_port
-这是nginx正在监听的端口(80),而不是请求端口。
$pass_port
-在我的设置中似乎为空,因此nginx删除了header 。
$http_port
-这是每个请求的随机端口。 $remote_port
-这是每个请求的随机端口。 我可以在部署时更改配置,以将代码硬编码到传入请求的已知端口,但是理想情况下,我可以更改前端端口,而无需更改nginx配置。
我搜寻了the nginx variable list,但是找不到类似
$request_port
的东西。有什么办法可以实现我的意图?
最佳答案
这只是编写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;
}
}
有关更多详细信息,请查看此项目https://github.com/dupinder/NgnixDockerizedDevEnv
关于docker - 如何将Nginx X-Forwarded-Port配置为原始请求端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60616564/