【问题标题】:How can i pass subdomain as proxy_pass value in nginx?如何在 nginx 中将子域作为 proxy_pass 值传递?
【发布时间】:2015-10-25 22:19:03
【问题描述】:

我目前处于需要获取/捕获子域并将该子域值传递给 Nginx 配置中的 proxy_pass 的情况。

例如

如果用户进入

http://google.com.mydomain.com

那么它应该做代理传递

proxy_pass http://www.google.com/;

在上面的例子中google.comsub-domain

这可行吗? 我如何在 nginx 中实现类似的功能?

目前我正在使用配置文件中的子域值是硬编码的,但是有很多子域,所以我需要这样做,但不知道正确的语法。

server {
    listen       80;
    server_name  subdomain.domain.com;
    charset utf-8;

    location / {
      proxy_pass http://www.subdomain/;
    }
}

我使用 * 作为 A 记录将所有子域重定向到我的网络主机,即通配符 DNS。

更新:

我从https://stackoverflow.com/a/22774520/1642018找到了代码sn-p

server {          
    listen       80;                                               
  # this matches every subdomain of domain.
  server_name .domain.com;                                           

  location / {                                                   

    set $subdomain "";

    if ($host ~* "^(.+)\.domain.com$") {                             
      set $subdomain $1;                                         
    }                                                            

    proxy_pass http://$subdomain;   

  }                                                              
} 

但请求显示的是我的默认页面,该页面位于我的默认 Web 根目录中。

【问题讨论】:

  • 这看起来可能是 XY 问题的情况:xyproblem.info。这是一个不寻常的要求。为什么不只服务子域?具体情况如何?很可能有比您所想的更好的解决方案
  • @Dayo 感谢您的回复,我想使用 nginx 作为我想要的任何域的反向代理,所以如果我输入 ebay.com.mydomain.com 它应该代理传递到 ebay.com 并充当反向代理并获得一个 ebay.com 页面。希望这会有所帮助。
  • 这不会与几乎任何域。尤其是像 google 或 ebay 这样的“大”网站

标签: nginx reverse-proxy proxypass


【解决方案1】:

如果定义了变量,我将使用映射然后代理传递来捕获子域:

map $host $subdomain {
    ~^(?<sub>.+)\.[^\.]+\.[^\.]+$ $sub;
}

server {          
    listen 80 default_server;
    server_name  _;

    location / {
        if ($subdomain) {
            proxy_pass http://$subdomain;   
        }                             
    }                                                              
}

【讨论】:

    【解决方案2】:

    两件事。

    1- 解析器(您的 nginx 的 dns 服务器以解析 google.com,您可以在您的主机上添加,或者您可以添加解析器语句)

    2- 您需要解决您的客户如何处理不同的域,我的意思是 google.com 与 google.com.ar 或 google.fr 不同)

    在这个例子中,我为你的例子 google.com 做了工作

    worker_processes 4;
    
    error_log /var/log/nginx/error.log;
    
    events {
      worker_connections  1024;
    }
    
    http {
    
      server {
        listen       80;
    
        location / { 
          set $subdomain ""; 
    
          if ($host ~* "^(.+)\.domain.com$") {
            set $subdomain $1; 
          }   
          resolver 8.8.8.8;
          proxy_pass "http://$subdomain.com";
    
        }   
      }
    }
    

    希望这个配置对你有帮助。

    【讨论】:

    猜你喜欢
    • 2017-11-13
    • 1970-01-01
    • 2020-10-20
    • 2014-05-11
    • 2019-10-23
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 2011-07-12
    相关资源
    最近更新 更多