使用 nginx 1.0 动态 proxy_pass 到 $var [英] Dynamic proxy_pass to $var with nginx 1.0

查看:34
本文介绍了使用 nginx 1.0 动态 proxy_pass 到 $var的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据环境变量将请求代理到不同的目标.我的方法是将目标 url 放入自定义变量 $target 并将其提供给 proxy_pass.

I am trying to proxy a request to different targets depending on an environment variable. My approach was to put the target url into the custom variable $target and give this to proxy_pass.

但是使用带有 proxy_pass 的变量似乎不起作用.这个简单的配置会导致来自 nginx 的502 Bad Gateway"响应.

But using a variable with proxy_pass doesn't seem to work. This simple config leads to a "502 Bad Gateway" response from nginx.

server {
  listen   8080;
  server_name  myhost.example.com;
  access_log  /var/log/nginx/myhost.access.log;
  location /proxy {
    set $target http://proxytarget.example.com;
    proxy_pass $target;
  }
}

没有变量的相同配置有效:

The same config without the variable works:

server {
  listen   8080;
  server_name  myhost.example.com;
  access_log  /var/log/nginx/myhost.access.log;
  location /proxy {
    proxy_pass http://proxytarget.example.com;
  }
}

这样使用proxy_pass真的不行还是我做错了什么?

Is it really not possible to use proxy_pass this way or am I just doing something wrong?

推荐答案

我最近自己偶然发现了这个需求,并发现为了在 proxy_pass 目标中使用变量,您需要将解析器设置为 error.log很可能包含类似 no resolver defined to resolve ...

I've recently stumbled upon this need myself and have found that in order to use variables in a proxy_pass destination you need to set a resolver as your error.log would most probably contain something like no resolver defined to resolve ...

我的解决方案是使用本地 DNS 进行 DNS 解析设置以下内容:

The solution in my case was to setup the following using a local DNS for DNS resolution:

location ~ /proxy/(.*) {
    resolver 127.0.0.1 [::1];
    proxy_pass http://$1;
}

在你的情况下,这应该有效:

In your case this should work:

location /proxy {
    resolver 127.0.0.1 [::1];
    set $target http://proxytarget.example.com;
    proxy_pass $target;
}

要使解析器 127.0.0.1 正常工作,您需要在本地安装 bind9.对于 Debian/Ubuntu:

For resolver 127.0.0.1 to work, you need to install bind9 locally. For Debian/Ubuntu:

sudo apt-get install bind9

sudo apt-get install bind9

有关 nginx 和动态 proxy_pass 的更多信息,请访问:http://www.nginx-discovery.com/2011/05/day-51-proxypass-and-resolver.html

More information on nginx and dynamic proxy_passing here: http://www.nginx-discovery.com/2011/05/day-51-proxypass-and-resolver.html

为安全起见,将之前的公共 DNS 替换为本地 DNS 问题.

Replaced the previous public DNS with a local one for security issues.

这篇关于使用 nginx 1.0 动态 proxy_pass 到 $var的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆