NGINX基于环境variables的基本authentication

我正在设置一个安装了nginx-lua的docker镜像。 该场景是在分段上进行基本身份validation,但不是在生产中。 我的想法是有一个ENVvariables与阶段的名称,并检查nginx.conf文件中的值。

docker-compose.yml文件的内容(当然,对于STAGE env来说,生产环境也是一样):

 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; } ... } } 

但它不工作。 任何想法,我怎么能做到这一点?

我只是从Serverfault的帮助find一个解决scheme。 这不是最好的,因为这些URL在nginx.conf文件中,但它解决了我的问题:

我刚刚删除了docker-compose.yml文件的variablesforms:

 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$1; proxy_set_header Host $api_base_uri; } ... } } 

如果有更好的/更好的解决scheme,请让我知道。