Nginx 拒绝IP访问
2015-01-29 by dongnan
举个栗子
拒绝某个IP地址访问nginx服务器
配置文件
# nginx.conf
deny 69.30.241.1xx;
重启服务
nginx -t && nginx -s reload
验证
# 查看日志
69.30.241.1xx - - [09/Dec/2014:12:20:19 +0800] "HEAD / HTTP/1.1" 403 0 "-" 
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)" -
返回 403 状态码。
Deny 与 Allow
只允许IP为 127.0.0.1访问,拒绝其它所有IP(白名单)。
location /nginx_stat {
    stub_status on;       # Turn on nginx stats
    access_log off;       # We do not need logs for stats
    allow 127.0.0.1;      # Security: Only allow access from IP
    deny all;             # Deny requests from the other of the world
}
注意执行的顺序
- 从上到下的顺序,类似
iptables,匹配到了规则便跳出。 - 如上例子只允许匹配的 
127.0.0.1,接下来未匹配的IP全部禁止访问。