auth_basic_module
参考:http://nginx.org/en/docs/http/ngx_http_auth_basic_module.html
Syntax: auth_basic string | off;
Default:
auth_basic off;
Context: http, server, location, limit_except
Syntax: auth_basic_user_file file;
Default: —
Context: http, server, location, limit_except
密码文件格式,密码支持明文和密文,密文使用openssl passwd或htpasswd生成
# comment
name1:password1
name2:password2:comment
name3:password3
案例一:
[root@imooc-nginx ~]# openssl passwd
Password:
Verifying - Password:
M1tFMmI.C8cHM
[root@imooc-nginx ~]# cat > /etc/nginx/passwd <<EOF
> admin:M1tFMmI.C8cHM
> EOF
**[root@imooc-nginx ~]# cat /etc/nginx/conf.d/www.uscwifi.cn.conf **
server {
listen 80;
listen 443 ssl;
server_name www.uscwifi.cn;
auth_basic pleaseinputpasswd;
auth_basic_user_file /etc/nginx/passwd;
if ($scheme = http){
return 301 https://$server_name$request_uri;
}
root /var/www/html;
index index.html;
access_log /var/log/nginx/www.uscwifi.cn-access.log;
error_log /var/log/nginx/www.uscwifi.cn-error.log;
ssl_certificate /etc/nginx/ssl/www.uscwifi.cn.crt;
ssl_certificate_key /etc/nginx/ssl/www.uscwifi.cn.key;
ssl_protocols SSLv3 TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS;
}
[root@imooc-nginx ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@imooc-nginx ~]# nginx -s reload

案例二:
我发现当http段和server段中都加auth_basic认证时,只有server生效
[root@imooc-nginx ~]# openssl passwd
Password:
Verifying - Password:
aJ7gzbKcmiru6
[root@imooc-nginx ~]# cat > /etc/nginx/passwd2 <<EOF
> admin:aJ7gzbKcmiru6
> EOF
**[root@imooc-nginx ~]# cat /etc/nginx/nginx.conf **
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$http_user_agent' '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
gzip on;
auth_basic "please input passwd";
auth_basic_user_file /etc/nginx/passwd2;
include /etc/nginx/conf.d/*.conf;
}
[root@imooc-nginx ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@imooc-nginx ~]# nginx -s reload

**案例三:还可以写在location内
[root@imooc-nginx conf.d]# openssl passwd -1
Password:
Verifying - Password:
$1$Jcc.l37e$bTv2EBFCAmQ4n/woecntJ0
[root@imooc-nginx conf.d]# cat > /etc/nginx/passwd <<'EOF'
admin:$1$Jcc.l37e$bTv2EBFCAmQ4n/woecntJ0
EOF
#不写了