【问题标题】:nginx location only for specific subdomain?nginx 位置仅适用于特定子域?
【发布时间】:2021-05-16 07:40:13
【问题描述】:

我继承了一个 nginx 配置,它是几百个独立的子域配置,所有这些都只是做一个 proxy_pass 并替换 proxy_pass 中的特定 ID,如下所示:

server {
  server_name somedomain.example.com;
  [snip]
  location / {
    proxy_pass http://localhost:7000/1234;
  }
}

明显的解决方案:切换到映射并像这样更改代码,消除所有重复的配置:

map $host $proj_id{
  somedomain.example.com 1234;
  otherdomain.example.com 2345;
}

server {
  server_name *.example.com;
  [snip]
  location / {
    proxy_pass http://localhost:7000/$proj_id;
  }
}

在这个过程中,我发现一些子域有这样的短网址重定向:

location = /someshorturl {
 return 301 https://asdf.example.com/[some-long-path-and-query];
}

这些短网址不是特定子域所独有的,因此我不能将它们作为通用配置中的一般规则。除了将这些域配置完全分开之外,还有什么方法可以真正说“如果域 = [那个特定的子域] 和位置 = / ...”?

【问题讨论】:

    标签: nginx


    【解决方案1】:

    所以我在 Reddit 上得到了答案……而且很简单,就是使用更多地图:

    map $host$uri $mapped_redirect {
      default 0;
      domain123.example.com/someshorturl https://domain.123.example.com/whatever;
    }
    
    server {
      if ($mapped_redirect) { return 301 $mapped_redirect; }
    }
    

    这很简洁,因为它允许在一个中心位置定义所有重定向,而不是大量单独的位置规则。

    【讨论】:

      猜你喜欢
      • 2023-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-13
      • 2018-12-07
      • 2018-01-13
      • 1970-01-01
      • 2012-06-03
      相关资源
      最近更新 更多