因为一些奇怪的需求,我要给我本地机上装的XAMPP中的Apache服务加个访问认证。
创建认证文件
使用命令行定位到C:\xampp\apache\conf
下
添加用户user1
,密码password123
C:\xampp\apache\bin\htpasswd.exe -bc users.pwd user1 password123
配置httpd.conf
我这边就直接加在默认配置底下了,有虚拟空间的看自己情况
<Location "/">
# Default to Basic Auth protection for any stie
AuthType Basic
AuthName "Auth"
AuthUserFile "C:\xampp\apache\conf\users.pwd"
Require valid-user
</Location>
给本地地址添加访问白名单
这认证我是配来防止别人乱来我这里搞事的,但不能我本地访问也要走一遍认证吧,多麻烦。
所以给访问控制规则加上两条
<Location "/">
# Default to Basic Auth protection for any stie
AuthType Basic
AuthName "Auth"
AuthUserFile "C:\xampp\apache\conf\users.pwd"
Require valid-user
# If the request goes to a rest page: bypass basic auth
Allow from 127.0.0.1
Allow from ::1 # Note Here
Order Deny,Allow
Satisfy any
Deny from all
</Location>
简单解释下整个规则的意思是源地址是本地环回IP的直接放行,其它地址的访问要求做认证。规则的顺序貌似没太大要求。
保存完配置重启Apache服务后就能应用了。
关于loaclhost地址的解析
现在的操作系统好像更喜欢把loaclhost解析成v6的地址::1
,Windows10和macOS都是这样。这个在配置时要尤其注意。漏掉v6地址的话容易看不出来导致时间浪费在排错上。