如果 htaccess 文件存在,我该如何应用基本身份验证?
如果首先尝试将auth_basic
指令放在一个if
块中,但这是不允许的。
然后,我尝试重定向到命名位置,但是虽然具有基本身份验证的位置工作正常,但重定向(在没有 htaccess 文件时发生)却出错。
该配置如下所示:
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"
我觉得这与一些变量被命名位置覆盖有关,但我不确定。
最后,我尝试alias
在命名位置使用,这样它们@foo
就不会成为搜索目录的一部分,但alias
不允许在命名位置使用……fuuuu
答案1
这就是MTecknology
和kolbyjack
建议我做的事#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;
}
}
工作完美!
答案2
延伸这个答案如果有多个/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;
}
}
}