1. 程式人生 > >Nginx實現基於ip的訪問控制(Ngx_http_access_module模塊)

Nginx實現基於ip的訪問控制(Ngx_http_access_module模塊)

nginx;web服務器;

Nginx實現基於ip的訪問控制功能:(Ngx_http_access_module)

官方文檔:http://nginx.org/en/docs/http/ngx_http_access_module.html

官方示例:

The ngx_http_access_module module allows limiting access to certain client addresses.限定資源只被指定的客戶端訪問。

Example Configuration:
location / {
    deny  192.168.1.1;        #自上而下檢測,匹配範圍小的在上面
    allow 192.168.1.0/24;
    allow 10.1.1.0/16;
    allow 2001:0db8::/32;
    deny  all;
}
Syntax:allow address | CIDR | unix: | all;
Default:
Context:http, server, location, limit_except
Syntax:deny address | CIDR | unix: | all;
Default:
Context:http, server, location, limit_except

Context:適用配置段


演示環境:

Server:192.168.47.140
Client1:192.168.47.137
Client2:192.168.47.138

[[email protected] ~]# cat /etc/redhat-release 
CentOS Linux release 7.2.1511 (Core) 
[[email protected] ~]# uname -r
3.10.0-327.el7.x86_64
[[email protected] ~]# nginx -V 
nginx version: nginx/1.10.2
......

相關配置:

#Server配置:
[[email protected] ~]# cat /data/html/server/index.html 
<h1>192.168.47.140</h1>
[[email protected] ~]# vim /etc/nginx/conf.d/Vhost.conf
server {
        listen 80;
        location /server/ {
                root /data/html/;
                allow 192.168.47.137;    #設定允許192.168.47.137
                deny all;                #拒絕所有
        }
}
[[email protected] ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[[email protected] ~]# nginx -s reload

#測試:
#Client(192.168.47.137)訪問:
[[email protected] ~]# ifconfig eno16777736 | grep "inet[[:space:]]" | sed ‘s/^.*et //g‘ | sed ‘s/netmask.*$//g‘
192.168.47.137  
[[email protected] ~]# curl http://192.168.47.140:/server/
<h1>192.168.47.140</h1>

#Client(192.168.47.138)訪問:
[[email protected] ~]# ifconfig eno16777736 | grep "inet[[:space:]]" | sed ‘s/^.*et //g‘ | sed ‘s/netmask.*$//g‘
192.168.47.138  
[[email protected] ~]# curl http://192.168.47.140:/server/
<html>
<head><title>403 Forbidden</title></head>
<body bgcolor="white">
<center><h1>403 Forbidden</h1></center>    #403 Forbidden權限拒絕。
<hr><center>nginx/1.10.2</center>
</body>
</html>


本文出自 “Gning丶” 博客,請務必保留此出處http://gning.blog.51cto.com/11847592/1968243

Nginx實現基於ip的訪問控制(Ngx_http_access_module模塊)