当前位置: 首页 > 后端技术 > PHP

Nginx基础知识(四)——Nginx请求限制与访问控制

时间:2023-03-29 21:52:41 PHP

Nginx请求限制与访问控制一、Nginx请求限制1、HTTP协议连接与请求HTTP协议版本与连接关系HTTP协议版本连接关系HTTP1.0TCP不能复用HTTP1.1sequentialTCPmultiplexingHTTP2.0multiplexingTCPmultiplexingHTTP请求建立在一个TCP连接的基础上。一个TCP连接至少可以产生一个HTTP请求。在HTTP1.1版本之后,可以建立一个TCP连接来发送多个HTTP请求。1.连接频率限制ngx_http_limit_conn_modulesyntaxSyntax:limit_conn_zonekeyzone=name:size;Default:—Context:httpSyntax:limit_connzonenumber;Default:—Context:http,server,locationUsage在nginx配置文件http下配置http{#...其他代码省略...#开辟一个10m的连接空间,命名为addrlimit_conn_zone$binary_remote_addrzone=addr:10m;server{...location/download/{#服务器一次只允许一个IP地址连接limit_connaddr1;}}}2。请求频率限制ngx_http_limit_req_moduleSyntax:limit_req_zonekeyzone=name:sizerate=rate;Default:—Context:httpSyntax:limit_reqzone=name[burst=number][nodelay];Default:—Context:http,server,locationUsage配置http在nginx配置文件中的http下{#...其他代码省略...#创建一个10m的请求空间,并命名为one.同一IP发送的请求每秒只处理一次limit_req_zone$binary_remote_addrzone=one:10mrate=1r/s;服务器{...位置/搜索/{limit_reqzone=one;#当客户端请求次数超过规定次数时,最多请求5次,并延迟处理,每秒1次请求#limit_reqzone=oneburst=5;#当客户端请求次数超过指定次数时,最多允许5次请求,立即处理。#limit_reqzone=oneburst=5nodelay;}}}二、Nginx访问控制1.基于IP的访问控制ngx_http_access_module语法语法:allowaddress|网段|Unix:|全部;默认值:—上下文:http、服务器、位置、limit_exceptSyntax:拒绝地址|网段|Unix:|all;Default:—Context:http,server,location,limit_exceptaddress:IP地址,例如:192.168.1.1CIDR:例如:192.168.1.0/24;unix:Socketmodeall:所有用法都在nginx配置文件server下配置{#...其他代码省略...location~^/index_1.html{root/usr/share/nginx/html;拒绝151.19.57.60;#拒绝此IP访问允许所有;#允许所有其他IP访问}location~^/index_2.html{root/usr/share/nginx/html;允许151.19.57.0/24;#允许IP151.19.57.*访问denyall;#DenyAllotherIPaccess}}ngx_http_access_module的限制当客户端通过代理访问时,nginx的remote_addr获取代理的IPhttp_x_forwarded_forhttp_x_forwarded_for=ClientIP,Proxy1IP,Proxy2IP,...remote_addr获取直连服务器客户端IP.http_x_forwarded_for可以记录客户端和所有中间代理的IP2。基于用户的登录认证ngx_http_auth_basic_module语法:auth_basicstring|离开;默认值:auth_basic关闭;上下文:http,server,location,limit_except,server,location,limit_except用法使用htpasswd命令需要先安装httpd-tools[root~]#yum-yinstallhttpd-tools使用htpasswd命令创建账号密码文件[root/etc/nginx]#htpasswd-c./auth_confauth_rootNewpassword:Re-typenewpassword:Addingpasswordforuserauth_root[root/etc/nginx]#llauth_conf-rw-r--r--1rootroot48July911:38auth_conf[root/etc/nginx]#catauth_confauth_root:$apr1$2v6gftlm$oo2LE8glGQWi68MCqtcN90在nginx配置文件server下配置server{#...其他代码省略...location~^/index.html{root/usr/share/nginx/html;auth_basic"授权访问!输入您的密码!";auth_basic_user_file/etc/nginx/auth_conf;}}修改后重新加载配置文件nginx-sreload使用浏览器访问http://192.168.33.88/index.html正确输入的用户名和密码,可以正常访问ngx_http_auth_basic_module的限制用户信息依赖文件方式运行管理效率低

最新推荐
猜你喜欢