1.创建用户名密码
创建用户名密码, 可以利用 apache 自带的 htpasswd 程序
htpasswd -c passwdfile username #多个passwdfile可以随便命名,最好不要保存到网站目录下
例如:
$ cd /usr/local/apache/bin
$ htpasswd -c /usr/local/apache/users/.htpasswd grace
2.开启htaccess权限
修改httpd.conf
<Directory "/var/www/html">
AllowOverride All #开启htaccess
Require all granted</Directory>
2.目录添加用户名和密码访问限制
在需要限制401访问的目录(/var/www/html/)下新建.htaccess 添加如下内容,用来限制访问
<Files ~ "^.(htaccess|htpasswd)$">
deny from all
</Files>
AuthName "Login" #这句话表示服务器弹出输入框的时候,会出现的提示
AuthType basic #表示使用基本认证模式
AuthUserFile "/usr/local/apache/users/.htpasswd" #用户名和密码文件路径
require valid-user #本目录需要用户认证才能访问
3. 如果一个目录启用的密码保护,想单独开放它的子目录
方法一:修改httpd.conf 对子目录单独配置开放限制
<Directory "/var/www/html">
AllowOverride All
Require all granted
</Directory>
<Directory "/var/www/html/opendir">
Satisfy All
Require all granted
</Directory>
方法二: 在子目录.htaccess文件中开放限制
<Files ~ "^.(htaccess|htpasswd)$">
Require all denied
</Files>
Satisfy All
Require all granted
4.通过PHP限制
<?php
date_default_timezone_set('Asia/Shanghai');
#通过用户名密码访问
#http://username:password@www.example.com/
#curl_setopt($ch, CURLOPT_USERPWD, 'username:password');
if(!isset($_SERVER['PHP_AUTH_USER']) || $_SERVER['PHP_AUTH_USER'] != 'grace' || $_SERVER['PHP_AUTH_PW']!='grace') {
header("Content-Type: text/html; charset=UTF-8");
header("WWW-Authenticate: Basic realm=\"Access to the staging site\"");
header("HTTP/1.0 401 Unauthorized");
exit;
}
echo "Welcome!!";