Nginx 访问控制
一.Nginx访问模块
1.访问控制模块:http_access_module:
nginx中内置ngx_http_access_module,可通过设置allow和deny来实现IP的访问控制。
[root@proxy ~]# vim /etc/nginx/nginx.conf
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
deny 192.168.73.129; #拒绝该IP访问我的Nginx服务器
allow all; #允许所有IP访问我的Nginx服务器
}
}
#deny:可以输入拒绝访问的IP或者是all禁止所有人
#allow:可以输入允许访问的IP或者all允许所有人
#也可以反向配置,或者输入网段192.168.0.0/24
#按顺序匹配,deny如果是all,下面的allow将不会在生效,反之也是一样
2.访问控制模块:http_auth_basic_module
Nginx提供HTTP的Basic Auth功能,配置了Basic Auth之后,需要输入正确的用户名和密码之后才能正确的访问网站。我们使用htpasswd来生成密码信息,首先要安装httpd-tools,在httpd-tools中包含了htpasswd命令。
[root@proxy ~]# vim /etc/nginx/nginx.conf
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
auth_basic "Auth access test!";
auth_basic_user_file /etc/nginx/auth_conf;
}
}
#anth_basic 不为off,开启登录验证功能
#auth_basic_user_file加载账号密码文件
#建立口令文件:需要httpd-tools软件支持
[root@proxy ~]# yum install -y httpd-tools
#htpasswd 是开源 http 服务器 apache httpd 的一个命令工具,用于生成 http 基本认证的密码文件。
固定写法:
htpasswd [参数] [passwd] [用户名] [密码]
-c添加用户
-bc不使用交互模式
-b在原有密码文件中生成一个新用户
-bn不更新密码文件,只将结果输出到屏幕
-D删除用户
-d修改用户密码,跟新增用户一样
#创建一个用户来进行实验
[root@proxy nginx]# htpasswd -cm /etc/nginx/auth_conf user01 #-c:创建加密文件; -m:MD5加密
New password:
Re-type new password:
Adding password for user user01
#浏览器访问
以上操作均实现了访问控制的效果,这对于我们的运维安全是由一定的实际效果的。