proxy_pass 中的 nginx 变量(cname) [英] nginx variables (cname) in proxy_pass

查看:530
本文介绍了proxy_pass 中的 nginx 变量(cname)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试动态设置 proxy_pass 目标,其中变量将是原始请求的 cname.

i am trying dynamically set a the proxy_pass destination where the variable would be the cname of the original request.

我现在拥有的是:

server {
    listen       8888;
    server_name (.*).domain.com;

    location / {
        proxy_pass       http://$1.otherdomain.com;
        proxy_set_header Host $1.otherdomain.com;

但不幸的是,这最终导致 502 错误网关.在 proxy_passproxy_set_header 中使用变量时,没有任何效果.

but unfortunately this ends up in a 502 bad gateway. nothing really works when using a variable in proxy_pass and proxy_set_header.

我也尝试在服务器名称和 $ 中使用 (?.+)(?P.+)cname 作为变量.

i also tried to use (?<cname>.+) or (?P<cname>.+) in the server name and $cname as the variable.

出了什么问题,为什么会以 502 结束?

what is wrong and why does it end up in a 502?

推荐答案

要在服务器名称中使用正则表达式,您需要在名称前加上波浪号~"

To use regex in server name, you need to prepend the name with a tilde "~"

server_name ~(.*).domain.com;

[更新]尝试了一下,它成功地将值设置为 1 美元.但仍然得到 502 并且我的 nginx 错误日志显示

[UPDATE] Tried it and it successfully set the value in $1. But still get 502 and my nginx error log shows

no resolver defined to resolve xyz.otherdomain.com

即使我将该名称指向我的/etc/hosts 文件中的本地主机.

even though I point that name to my localhost in my /etc/hosts file.

找到这篇文章很好地解释了这个问题.基本上在这种特殊情况下(上游域名中的变量),您需要使用 "resolver" 指令 指向可以解析此动态域名的 dns 服务器(例如,来自 google dns 服务器的 8.8.8.8).

Find this article that explains this issue well. Basically in this special case (variable in upstream domain name), you need to use the "resolver" directive to point to a dns server (e.g., 8.8.8.8 from google dns server) that can resolve this dynamic domain name.

resolver 8.8.8.8;

它在我的测试中使用公共上游域名.如果你的上游域名是本地的,你需要为它们设置一个本地的dns服务器.

It works in my test with a public upstream domain name. If you upstream domain names are local, you need to set up a local dns server for them.

这篇关于proxy_pass 中的 nginx 变量(cname)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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