【问题标题】:Is is possible to define a single nginx location in two separate blocks?是否可以在两个单独的块中定义单个 nginx 位置?
【发布时间】:2017-04-07 16:02:01
【问题描述】:

是否可以在两个单独的块中定义单个 nginx 位置?

例如:

server {
  listen *:80;
  server_name someserver;

  location / {
    proxy_cache off;
  }

  location /assets {
    proxy_cache mycache;
  }

  # What do I need to do to get this second root location
  # to append to the 1st? If it's even possible.
  location / {
    proxy_pass http://foo;
  }
}

这个想法是根位置有效地变成:

location / {
  proxy_cache off;
  proxy_pass http://foo;
}

如果您想了解更多原因,请继续阅读。


背景:

我正在运行 GitLab Omnibus 安装。根据docs,管理员将自定义 nginx 配置注入到 GitLab 服务器块。

但是,这种注入会将内容添加到终端服务器块而不是特定的位置块。

所以如果我尝试注入include my_config.conf;,我会得到:

server {
  listen *:80;
  server_name someserver;

  location / {
    proxy_cache off;
  }

  location /assets {
    proxy_cache mycache;
  }

  include my_config.conf;
}

如果我尝试包含location ^~ / {\n include my_config.conf;\n }\n,我会得到:

server {
  listen *:80;
  server_name someserver;

  location / {
    proxy_cache off;
  }

  location /assets {
    proxy_cache mycache;
  }

  location ^~ / {
    include my_config.conf;
  }
}

这会导致 nginx 配置失败并出现 duplicate location "/" in /var/opt/gitlab/nginx/conf/gitlab-http.conf:106 错误。

注意: my_config.conf 包含用于 CORS 的 add_header 内容,因此它必须是 in a location block。

【问题讨论】:

    标签: nginx


    【解决方案1】:

    您可能需要了解nginx processes a request 的原理。但是位置块是不相加的,必须单独完成。您可以将某些语句放在 server 块中,并允许单独的 location 块根据需要覆盖(例如 proxy_cache)。

    假设你所有的 URI 都被代理了,你可以使用这样的东西:

    proxy_cache off;
    
    location / {
        proxy_pass http://foo;
    }
    location /assets {
        proxy_cache mycache;
        proxy_pass http://foo;
    }
    

    可以将常用语句卸载到include 文件中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-20
      • 2014-10-27
      • 1970-01-01
      • 1970-01-01
      • 2015-06-27
      • 2012-03-01
      • 2016-05-11
      相关资源
      最近更新 更多