Nginx – 仅在存在htaccess文件时才应用基本身份validation

我如何才能应用基本身份validation只有当一个htaccess文件存在?

如果第一次尝试将auth_basic指令放在一个if块中,但这是不允许的。

然后,我尝试redirect到一个命名的位置,但是当基本身份validation的位置正常工作时,redirect(发生在没有htaccess文件时)正在出错。

这是什么configuration看起来像:

 server { listen 80; server_name ~^(?<instance>.+?)\.foo.example.com$; set $htaccess_user_file /var/htaccess/$instance.foo.example.com.htaccess; if (!-f $htaccess_user_file) { rewrite ^ @foo; } location / { auth_basic "Restricted"; auth_basic_user_file $htaccess_user_file; root /var/www/$instance.foo.example.com; try_files $uri /index.html =404; } location @foo { root /var/www/$instance.foo.example.com; try_files $uri /index.html =404; } } 

这里是我没有htaccess文件时得到的错误消息:

 2013/07/12 08:37:08 [error] 32082#0: *192 open() "/usr/html@foo" failed (2: No such file or directory), client: 1.2.3.4, server: ~^(?<instance>.+?)\.foo.example.com$, request: "GET / HTTP/1.1", host: "bar.foo.example.com" 

我有一种感觉,它与一些variables被命名的位置覆盖,但我不知道。

最后,我尝试在命名的位置使用alias ,这样的@foo不会是search目录的一部分,但alias不允许在命名的位置…. fuuuu

这就是MTecknologykolbyjackbuild议我在#nginx上做的#nginx

 server { listen 80; server_name ~^(?<instance>.+?)\.foo.example.com$; root /var/www/$instance.foo.example.com; set $htaccess_user_file /var/htaccess/$instance.foo.example.com/.htaccess; if (!-f $htaccess_user_file) { return 599; } location / { auth_basic "Restricted"; auth_basic_user_file $htaccess_user_file; try_files $uri /index.html =404; } error_page 599 = @foo; location @foo { root /var/www/$instance.foo.example.com; try_files $uri /index.html =404; } } 

工作完美无瑕!

如果您有多个/location条目,则需要将if块移动到相关位置。

 worker_processes 1; events { worker_connections 1024; accept_mutex off; use epoll; } http { include mime.types; default_type application/octet-stream; sendfile on; upstream app_server { server localhost:8000 fail_timeout=0; } server { listen 80; set $htaccess_user_file /etc/secrets/nginx-proxy/htaccess; error_log stderr info; keepalive_timeout 5; location /static { expires 30d; add_header Pragma public; add_header Cache-Control "public"; autoindex off; alias /mnt/static/; gzip on; gzip_buffers 16 8k; gzip_comp_level 9; gzip_http_version 1.0; gzip_min_length 0; gzip_types text/plain text/css image/x-icon image/svg+xml image/png image/jpg image/jpeg text/js application/javascript application/x-javascript; gzip_vary on; gzip_proxied expired no-cache no-store private auth; gzip_disable "MSIE [1-6]\."; } location /media { autoindex off; alias /mnt/media/; } error_page 599 = @noauth; location / { if (!-f $htaccess_user_file) { return 599; } auth_basic "Restricted"; auth_basic_user_file $htaccess_user_file; try_files $uri @proxy_to_app; } location @noauth { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto; proxy_set_header Host $http_host; proxy_redirect off; proxy_buffering off; proxy_pass http://app_server; } } }