And*_*bbs 23 reverse-proxy nginx docker x-forwarded-for nginx-reverse-proxy
我在标准反向代理场景中使用 nginx,将所有请求传递/auth
到另一台主机,但是我正在尝试使用非标准端口。
我的最终目标是将X-Forwarded-Port
标头设置为请求进入的端口。
这是我在 nginx.conf 中的位置块:
Run Code Online (Sandbox Code Playgroud)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
标题丢失或错误。
在<VAR>
原始块中,我尝试了以下操作:
$server_port
- 这是 nginx 正在侦听的端口 (80),而不是请求端口。
$pass_port
- 在我的设置中似乎为空,因此 nginx 删除了标头。
$http_port
- 这是每个请求的随机端口。
$remote_port
- 这是每个请求的随机端口。
我可以在部署时将我的配置更改为硬编码到传入请求的已知端口,但理想情况下,我将能够更改前端端口,而无需对 nginx 配置进行任何更改。
我已经搜索了 nginx 变量列表,但找不到类似$request_port
. 有什么方法可以实现我的意图吗?
我发现的唯一解决方法是使用map
规则从http_host
变量中获取端口,例如
map $http_host $port {
default 80;
"~^[^\:]+:(?<p>\d+)$" $p;
}
Run Code Online (Sandbox Code Playgroud)
这是编写 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)
归档时间: |
|
查看次数: |
13800 次 |
最近记录: |