限制:ngx_http_limit_req_module
一、测试未限制情况下的访问
[root@nginx ~]# yum install -y httpd-tools
[root@nginx ~]# ab -n 100 -c 10 http://yangyonglin/
This is ApacheBench, Version 2.3 <$Revision: 1430300 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/
Benchmarking yangyonglin (be patient).....done
Server Software: nginx/1.22.1
Server Hostname: yangyonglin
Server Port: 80
Document Path: /
Document Length: 22 bytes
Concurrency Level: 10
Time taken for tests: 0.021 seconds
Complete requests: 100
Failed requests: 0
Write errors: 0
Total transferred: 25300 bytes
HTML transferred: 2200 bytes
Requests per second: 4652.89 [#/sec] (mean)
Time per request: 2.149 [ms] (mean)
Time per request: 0.215 [ms] (mean, across all concurrent requests)
Transfer rate: 1149.59 [Kbytes/sec] received
......
二、配置
[root@nginx ~]# vim /etc/nginx/nginx.conf
......
http {
limit_req_zone $binary_remote_addr zone=yyl:10m rate=1r/s;
限制请求 二进制地址 限制策略的名称 占用10M空间 允许每秒1次请求
[root@nginx ~]# vim /etc/nginx/conf.d/yyl.conf
location / {
......
limit_req zone=yyl;
引用 限制策略的名称
三、重启服务,并测试
四、观察错误日志
[root@nginx ~]# tail -f /var/log/nginx/error.log
2022/12/31 15:58:28 [error] 90077#90077: *302 limiting requests, excess: 0.993 by zone "yyl", client: 192.168.163.128, server: yangyonglin, request: "GET / HTTP/1.0", host: "yangyonglin"
控制:ngx_http_access_module
一、启用控制
(一)基于主机
#限制主机访问
[root@nginx ~]#vim /etc/nginx/conf.d/default.conf
server {
allow 192.168.163.132;
allow 192.168.163.135;
deny all;
}
#重启
[root@nginx ~]#systemctl restart nginx
(二)基于用户
[root@nginx ~]#yum install -y httpd-tools
#生成秘钥的工具是由apache提供
[root@nginx ~]#htpasswd -cm /etc/nginx/conf.d/passwd user10
#会话密码
[root@nginx ~]#cat /etc/nginx/conf.d/passwd
#观察口令文件是否生成
vim /etc/nginx/conf.d/default.conf
server {
auth_basic "nginx access test!";
auth_basic_user_file /etc/nginx/conf.d/passwd;
#提示消息引用认证文件
...
}
[root@nginx ~]#systemctl restart nginx