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

时间:2016-07-11 15:01:07

标签: nginx docker lua docker-compose nginx-location

我设置了一个安装了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$1;
      proxy_set_header Host $api_base_uri;
    }

    ...

  }

}

但它没有用。任何想法,我怎么能实现这个目标?

1 个答案:

答案 0 :(得分:2)

我只是在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"

然后我在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$1;
      proxy_set_header Host $api_base_uri;
    }

    ...

  }

}

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