上一篇博客介绍了Nginx添加第三方模块并实现平滑启动 其中留下了一个问题?
监控Nginx服务器运行情况的模块。只要用户在浏览器输入http://your_ip/status
,就可以访问监控页面。这样很不安全,因为任何人都可以访问这个页面。是否可以再添加一个授权模块呢?
答案是肯定的,Nginx的源码
提供了ngx_http_auth_basic_module
这个模块,它可以来解决这个问题。这个模块是默认就编译进nginx的,可以直接拿来使用。
ngx_http_auth_basic_module
它提供了最基本的http认证,这是http协议支持的,它会弹出一个框让你输入用户名和密码,只有用户名和密码输入正确了才能访问,这样就能防止http://your_ip/status
被任何人访问了。
ngx_http_auth_basic_module
是使用文件作为存储介质的,用户名是明文存储,而密码是加密之后再存储,这样在认证框输入的用户名和密码必须和文件的信息匹配才能认证成功。这里使用htpasswd
这个命令来生成存放用户名和密码的文件。
什么是 htpasswd ?
htpasswd 是开源 http 服务器 apache httpd 的一个命令工具,用于生成 http 基本认证的密码文件。
安装
ubuntu
sudo apt-get install apache2-utils
centos
yum -y install httpd
使用
语法
htpasswd(选项)(参数)
htpasswd 选项说明
-c 创建passwdfile.如果passwdfile 已经存在,那么它会重新写入并删去原有内容.
-n 不更新passwordfile,只将加密后的用户名密码显示在屏幕上;
-m 默认采用MD5算法对密码进行加密
-d 采用CRYPT算法对密码进行加密
-p 不对密码进行进行加密,即使用普通文本格式的密码
-s 采用SHA算法对密码进行加密
-b 命令行中一并输入用户名和密码而不是根据提示输入密码,可以看见明文,不需要交互
-D 删除指定的用户
htpasswd 参数说明
- 用户:用户名
- 密码:用户的密码
实例
利用htpasswd命令添加用户
shell> htpasswd -c /usr/local/nginx/.htpasswd Javen
New password:
Re-type new password:
Adding password for user Javen
或者不用交互的模式
shell> htpasswd -bc /usr/local/nginx/.htpasswd Javen javen205
在/usr/local/nginx/
目录下生成一个.htpasswd
文件,用户名Javen
,密码javen205
,默认采用MD5加密方式。
在原有密码文件中增加下一个用户
去掉
-c
选项即可在第一个用户之后添加第二个用户
shell> htpasswd -b /usr/local/nginx/.htpasswd JJ jj
不更新密码文件,只显示加密后的用户名和密码
不更新.passwd文件,只在屏幕上输出用户名和经过加密后的密码。
shell> htpasswd -nb Javen Javen205
利用htpasswd命令删除用户名和密码
shell> htpasswd -D /usr/local/nginx/.htpasswd Javen
Deleting password for user Javen
利用htpasswd命令修改密码
htpasswd
并没有直接修改密码的函数,需要先使用htpasswd删除命令删除指定用户,再利用htpasswd添加用户命令创建用户即可实现修改密码的功能。
htpasswd -D .htpasswd Javen
htpasswd -b .htpasswd Javen javen205
Nginx中使用htpasswd
在配置文件中打开http basic auth认证。
location /status {
auth_basic "Restricted";
auth_basic_user_file /usr/local/nginx/.htpasswd;
vhost_traffic_status_display;
vhost_traffic_status_display_format html;
}
效果图
个人能力有限如有错误欢迎指正。你有更好的解决方案或者建议欢迎一起交流讨论,如有疑问欢迎留言。