Nginx访问控制
如何去做一些特殊的访问的控制?例如禁止来自攻击IP的访问,登录管理页面设置管理员IP即白名单,该如何去做呢?
Nginx访问控制一行一行过滤,匹配到规则后,直接执行,后面的规则不再重复匹配,区别Apache的order指定allow和deny的匹配先后顺序。
一、编辑虚拟主机的配置文件,
1、针对location模块白名单
[root@daixuan vhosts]# vim test.conf
location ~ .*admin\.php$ {
allow 127.0.0.1; //只允许127.0.0.1访问,
deny all; //其他拒绝,deny all必须得写
include fastcgi_params;
fastcgi_pass unix:/tmp/www.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /data/www$fastcgi_script_name;
}
[root@daixuan vhosts]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@daixuan vhosts]# /etc/init.d/nginx reload
重新载入 Nginx: [确定]
[root@daixuan vhosts]# /etc/init.d/nginx restart
停止 Nginx: [确定]
正在启动 Nginx: [确定]
[root@daixuan vhosts]# curl -x127.0.0.1:80 www.test.com/admin.php -I
HTTP/1.1 200 OK 127.0.0.1可以访问admin.php
Server: nginx/1.8.0
[root@daixuan vhosts]# curl -x192.168.101.230:80 www.test.com/admin.php -I
HTTP/1.1 403 Forbidden 其他的任何IP都无法访问
Server: nginx/1.8.0
2、有时候也会根据目录来限制php解析:
location ~.*(dig|template|attachment|forumdata|attachment|image)/.*\.php$
{
deny all;
}
二、针对全局
1、针对全局设置白名单
[root@daixuan vhosts]# vim test.conf
server
{
listen 80;
server_name www.test.com www.aaa.com www.bbb.com;
if ($host != 'www.test.com'){
rewrite ^/(.*)$ http://www.test.com/$1 permanent;
}
index index.html index.htm index.php;
root /data/www;
access_log /tmp/access.log daixuan;
allow 192.168.101.0/24; //白名单设置192.168.101.0网段允许访问,其他全部拒绝
deny all; //deny必须得写
[root@daixuan vhosts]# curl -x192.168.101.230:80 www.test.com -I
[root@daixuan vhosts]# curl -x127.0.0.1:80 www.test.com -I
HTTP/1.1 403 Forbidden
[root@daixuan vhosts]# curl -x192.168.101.230:80 www.test.com -I
HTTP/1.1 301 Moved Permanently
2、针对全局设置黑名单
[root@daixuan vhosts]# vim test.conf
server
{
listen 80;
server_name www.test.com www.aaa.com www.bbb.com;
if ($host != 'www.test.com'){
rewrite ^/(.*)$ http://www.test.com/$1 permanent;
}
index index.html index.htm index.php;
root /data/www;
access_log /tmp/access.log daixuan;
deny 127.0.0.1; //设置黑名单,默认allow all可以不写
//allow all;
}
[root@daixuan vhosts]# /etc/init.d/nginx reload
[root@daixuan vhosts]# curl -x127.0.0.1:80 www.test.com -I
HTTP/1.1 403 Forbidden
[root@daixuan vhosts]# curl -x192.168.101.230:80 www.test.com -I
HTTP/1.1 301 Moved Permanently