一.基于主机访问控制
1.修改nginx.conf文件
2.到其他主机上测试
(1)191主机
(2)180主机
二.基于用户访问控制
1.修改nginx.conf文件
2.使用hpasswd为用户创建密码文件,并指定到刚才指定的密码文件webck
3.测试
三.缓存配置
一.基于主机访问控制
1.修改nginx.conf文件
修改server区块内的location块,deny表示禁止这台主机访问,allow表示允许,可以使用all表示禁止/允许所有,一定要注意匹配顺序是从上至下,下例也就表示允许除2.191外的主机访问
server {
listen 192.168.2.190;
server_name www.aabb.com;
error_log /usr/local/src/nginx-1.22.0/logs/error.log;
access_log /usr/local/src/nginx-1.22.0/logs/access.log;
location / {
root /usr/local/src/nginx-1.22.0/html/ip;
index index.html index.htm;
deny 192.168.2.191;
allow all;
#deny 192.168.2.0/24; 可以指定一个网段
}
}
[root@localhost conf]# systemctl restart nginx.service
2.到其他主机上测试
(1)191主机
[root@localhost ~]# ip a | grep ens33
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
inet 192.168.2.191/24 brd 192.168.2.255 scope global noprefixroute ens33
[root@localhost ~]# curl 192.168.2.190
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.22.0</center>
</body>
</html>
(2)180主机
[root@localhost ~]# ip a | grep ens160
2: ens160: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
inet 192.168.2.180/24 brd 192.168.2.255 scope global noprefixroute ens160
[root@localhost ~]# curl 192.168.2.190
190
二.基于用户访问控制
1.修改nginx.conf文件
server {
listen 192.168.2.190;
server_name www.aabb.com;
error_log /usr/local/src/nginx-1.22.0/logs/error.log;
access_log /usr/local/src/nginx-1.22.0/logs/access.log;
location / {
root /usr/local/src/nginx-1.22.0/html/ip;
index index.html index.htm;
allow all;
auth_basic "here"; #加上这两行,这行是出现在第一次访问Nginx站点的弹出框内
auth_basic_user_file /usr/local/src/nginx-1.22.0/conf/webck; #指定密码文件
}
}
[root@localhost conf]# pwd
/usr/local/src/nginx-1.22.0/conf
[root@localhost conf]# ll | grep webck
-rw-r--r-- 1 root root 22 Aug 10 18:54 webck
2.使用hpasswd为用户创建密码文件,并指定到刚才指定的密码文件webck
[root@localhost conf]# htpasswd -c -d /usr/local/src/nginx-1.22.0/conf/webck sulibao
New password:
Re-type new password:
Warning: Password truncated to 8 characters by CRYPT algorithm.
Adding password for user sulibao
[root@localhost conf]# cat webck
sulibao:8sWMglgDCLsGQ #密码已加密
[root@localhost conf]# systemctl restart nginx
3.测试
三.缓存配置
expires参数,下例表示对以这些后缀结尾的图片文件缓存30天
server {
listen 192.168.2.190;
server_name www.aabb.com;
error_log /usr/local/src/nginx-1.22.0/logs/error.log;
access_log /usr/local/src/nginx-1.22.0/logs/access.log;
location / {
root /usr/local/src/nginx-1.22.0/html/ip;
index index.html index.htm;
allow all;
auth_basic "here";
auth_basic_user_file /usr/local/src/nginx-1.22.0/conf/webck;
}
location ~ .*\.(gif|jpg|png)$ {
expires 30d;
}
}