您可以使用 Nginx map 指令来做到这一点,它允许您根据另一个变量设置一个变量。
在您的 html 块内,但在您设置地图指令的任何服务器块之外
map $cookie_trustedclient $mysite_authentication {
default "Your credentials please";
secret-cookie-value off;
}
这里发生的是 Nginx 正在根据名为 trustedclient 的 cookie 的值设置自定义变量 $mysite_authentication 的值。
默认情况下$mysite_authentication 将设置为Your credentials please,除非您有一个名为trustedclient 且值为secret-cookie-value 的cookie,在这种情况下$mysite_authentication 将设置为off
现在,在您启用基本身份验证的位置块中,您可以更改 auth_basic 指令以使用新变量,如下所示:
location /secretfiles {
auth_basic $mysite_authentication;
auth_basic_user_file ....
add_header Set-Cookie "trustedclient=secret-cookie-value;max-age=3153600000;path=/";
}
您可以在此处或在您的网站代码中设置 cookie。结果是 auth_basic 指令被设置为 off 对于拥有正确 cookie 的人,或者对于没有它的人的密码框显示消息。
不是超级安全,但对于大多数事情来说简单且足够好。
从您的配置中编辑:
# Map block can go here
map $cookie_trustedclient $mysite_authentication {
default "Your credentials please";
secret-cookie-value off;
}
server {
listen 443 ssl default_server;
listen [::]:443 ssl default_server;
# ssl on; # Delete this line, obsolete directive
ssl_certificate /etc/nginx/cloudflare-ssl/certificate.pem;
ssl_certificate_key /etc/nginx/cloudflare-ssl/key.key;
ssl_client_certificate /etc/nginx/cloudflare-ssl/cloudflare.crt;
ssl_verify_client on;
root /var/www/html;
index index.html index.htm index.nginx-debian.html;
server_name ********.com;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ =404;
# auth_basic "Restricted Content"; # Now this becomes:
auth_basic $mysite_authentication;
auth_basic_user_file /etc/nginx/.htpasswd;
add_header Set-Cookie "trustedclient=secret-cookie-value;max-age=3153600000;path=/";
}
}