我似乎无法在 nginx 上进行基本身份验证。有人能指出哪里出了问题吗?
.htpasswd 的权限/所有权
ubuntu@ubuntu-GB-BXi3-5010:~$ sudo ls -lah /etc/nginx/.htpasswd
-r-xr-x--- 1 root www-data 45 Aug 6 13:22 /etc/nginx/.htpasswd
.htpasswd 的内容
ubuntu@ubuntu-GB-BXi3-5010:~$ sudo cat /etc/nginx/.htpasswd
robert:$apr1$v6WW9OCq$gRlr0640ZnacROOpyGzsQ0
nginx 默认站点的内容
ubuntu@ubuntu-GB-BXi3-5010:~$ sudo cat /etc/nginx/sites-enabled/default
server {
listen 80 default_server;
root /var/www/html;
index index.html index.htm index.nginx-debian.html;
server_name _;
location /api {
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/.htpasswd;
return 201;
}
}
确保 nginx 已重新启动:
ubuntu@ubuntu-GB-BXi3-5010:~$ sudo systemctl restart nginx
在打开详细功能的情况下通过 CURL 向服务器发送请求,结果直接返回 201 代码 - 没有向服务器发送任何基本身份验证信息:
ubuntu@ubuntu-GB-BXi3-5010:~$ curl --verbose http://127.0.0.1/api
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to 127.0.0.1 (127.0.0.1) port 80 (#0)
> GET /api HTTP/1.1
> Host: 127.0.0.1
> User-Agent: curl/7.61.0
> Accept: */*
>
< HTTP/1.1 201 Created
< Server: nginx/1.16.0
< Date: Tue, 06 Aug 2019 03:23:26 GMT
< Content-Type: application/octet-stream
< Content-Length: 0
< Connection: keep-alive
<
* Connection #0 to host 127.0.0.1 left intact
nginx版本是1.16.0
ubuntu@ubuntu-GB-BXi3-5010:~$ nginx -v
nginx version: nginx/1.16.0
nginx安装的模块:
ubuntu@ubuntu-GB-BXi3-5010:~$ nginx -V 2>&1 | tr -- - '\n' | grep module
modules
path=/usr/lib/nginx/modules
http_addition_module
http_auth_request_module
http_dav_module
http_flv_module
http_gunzip_module
http_gzip_static_module
http_mp4_module
http_random_index_module
http_realip_module
http_secure_link_module
http_slice_module
http_ssl_module
http_stub_status_module
http_sub_module
http_v2_module
mail_ssl_module
stream_realip_module
stream_ssl_module
stream_ssl_preread_module
ubuntu@ubuntu-GB-BXi3-5010:~$
答案1
当然,下班后,我一发布就找到了答案:
看起来基本身份验证指令需要位于位置块的底部,原因我不明白:
server {
listen 80 default_server;
root /var/www/html;
index index.html index.htm index.nginx-debian.html;
server_name _;
location /api {
return 201;
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/.htpasswd;
}
}