Nginx 实现 HTTP 用户认证
当某些内容只想给某些特定的用户看到的话,HTTP 用户认证是一个很好的解决方法。下面是在 Nginx 实现 HTTP 用户认证方法。
用户密码信息要保存到一个文件中供 Nginx 调用,先创建一个文件夹保存这些文件
[root@lnmp lnmp.cn]# mkdir /etc/nginx/htpasswd
而这个文件通常可以用 Apache htpasswd 生成,但这里既然已经装了 Nginx,就不想再装 Apache 了,在没安装 Apache 的情况,可以通过如下命令通过 openssl 生成 htpasswd 文件:
[root@lnmp lnmp.cn]# printf "lnmp:$(openssl passwd -crypt lnmp.cn)\n" >> /etc/nginx/htpasswd/lnmp.cn
其中 lnmp 是用户名,lnmp.cn 是密码。其中密码有长度限制,最长8位,超过会被截断,并出现这个警告:
Warning: truncating password to 8 characters
可以继续以上命令创建多个用户,只要用户名不要重复,重复的话只会第一个有效
[root@lnmp lnmp.cn]# printf "lnmp.cn:$(openssl passwd -crypt lnmp.cn8)\n" >> /etc/nginx/htpasswd/lnmp.cn
[root@lnmp lnmp.cn]# cat /etc/nginx/htpasswd/lnmp.cn
lnmp:7YlY0mej1RzLc
lnmp.cn:LsVZ/JLOUkbm.
[root@lnmp lnmp.cn]#
创建好 htpasswd 文件只会,在想要加认证的 location 中加入如下配置
auth_basic "http auth for lnmp.cn";
auth_basic_user_file /etc/nginx/htpasswd/lnmp.cn;
autoindex on;
以下是完整 Nginx 配置文件示例
server {
listen 80;
server_name www.lnmp.cn;
root /www/lnmp.cn/web;
location / {
index index.php index.html index.htm;
auth_basic "http auth for lnmp.cn";
auth_basic_user_file /etc/nginx/htpasswd/lnmp.cn;
autoindex on;
}
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
修改好配置之后,务必 reload nginx 才会生效
[root@lnmp lnmp.cn]# systemctl reload nginx
打开网址就会要求输入用户和密码了
前一篇: CentOS 7 下 PHP 7,MySQL 5.7 和 Nginx 1.8 的安装与配置
后一篇: FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream