基于环境变量的NGINX基础认证

NGINX basic authentication based on environment variable

我正在设置一个安装了 nginx-lua 的 docker 映像。该场景是在登台时进行基本身份验证,但在生产中不进行。我的想法是拥有一个带有舞台名称的 ENV 变量,并检查 nginx.conf 文件中的值。

docker-compose.yml 文件的内容(对于暂存和生产,STAGE 环境当然是 prod):

docs-router:
  build: ./nginx 
  environment:
    - API_BASE_URI=staging.example.com
    - DOCS_STATIC_URI=docs-staging.example.com
    - STAGE=staging
  ports:
    - "8089:8089"
    - "8090:8090"

nginx.conf 文件的内容:

...

env API_BASE_URI;
env DOCS_STATIC_URI;
env STAGE;

...

http {
  server {
    listen 8089 default_server;
    charset utf-8;
    resolver 8.8.8.8;
    access_log off;

    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    location ~ ^(/.*\.(?:apib|svg))?$ {
      set_by_lua_block $api_base_uri { return os.getenv("API_BASE_URI") }
      set_by_lua_block $stage { return os.getenv("STAGE") }
      set $unprotected "prod";

      if ($stage = $unprotected) {
        auth_basic "Restricted Content";
        auth_basic_user_file /etc/nginx/.htpasswd;
      }

      proxy_pass https://$api_base_uri;
      proxy_set_header Host $api_base_uri;
    }

    ...

  }

}

但它不起作用。知道吗,我怎样才能做到这一点?

我只是在 Serverfault 的帮助下找到了解决方案。它不是最好的,因为 URL 在 nginx.conf 文件中,但它解决了我的问题:

我刚刚从 docker-compose.yml 文件中删除了变量:

docs-router:
  build: ./nginx 
  environment:
    - API_BASE_URI=staging.example.com
    - DOCS_STATIC_URI=docs-staging.example.com
  ports:
    - "8089:8089"
    - "8090:8090"

然后我将 URL 映射到 nginx.conf 文件中:

...

env API_BASE_URI;
env DOCS_STATIC_URI;

...

http {

  ##
  # URL protection
  ##
  map $http_host $auth_type {
    default "off";
    stage1.example.com "Restricted";
    stage2.example.com "Restricted";
  }

  server {
    listen 8089 default_server;
    charset utf-8;
    resolver 8.8.8.8;
    access_log off;

    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header Host $http_host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    location ~ ^(/.*\.(?:apib|svg))?$ {
      set_by_lua_block $api_base_uri { return os.getenv("API_BASE_URI") }

      auth_basic $auth_type;
      auth_basic_user_file /etc/nginx/.htpasswd;

      proxy_pass https://$api_base_uri;
      proxy_set_header Host $api_base_uri;
    }

    ...

  }

}

如果对此有更好/更好的解决方案,请告诉我。