centos7.4 源码搭建LNMP___Nginx配置——2:防盗链、访问控制

学习笔记

1、Nginx防盗链

编辑配置文件

vim /usr/local/nginx/conf/vhost/test.com.conf
server
{   listen 80;
           server_name test.com test1.com;
           index index.html index.htm index.php;
           root /data/nginx/test.com;

           location  /admin/
           {
               auth_basic              "Auth";
               auth_basic_user_file   /usr/local/nginx/conf/htpasswd;
           }


           if ($host != 'test.com' ) {
               rewrite  ^/(.*)$  http://test.com/$1  permanent;
           }


           location ~* ^.+\.(gif|jpg|png|swf|flv|rar|zip|doc|pdf|gz|bz2|jpeg|bmp|xls)$
           {
               expires 7d;
               valid_referers none blocked server_names  *.test.com ;
               if ($invalid_referer) {
                   return 403;
               }
               access_log off;
           }


           access_log /tmp/test.log combined_realip;


}

测试、重启、验证

/usr/local/nginx/sbin/nginx -t
/usr/local/nginx/sbin/nginx -s reload
curl -x127.0.0.1:80 -I -e "http://baidu.com/1.txt" test.com/02.jpg
curl -x127.0.0.1:80 -I -e "http://test.com/1.txt" test.com/02.jpg

结果

 

2、访问控制

2.1、访问的目录 /data/nginx/test.com/admin/

         编辑配置文件

vim /usr/local/nginx/conf/vhost/test.com.conf
#添加以下代码
           location /admin/
           {
               deny 127.0.0.1;

           }

这是拒绝某个IP访问


/usr/local/nginx/sbin/nginx -t
/usr/local/nginx/sbin/nginx -s reload

验证

curl -x127.0.0.1:80 test.com/admin/index.html

结果


如果是允许某个IP访问(也可以写成allow 192.168.233.0/24)

#插入以下代码
           location /admin/
           {
               allow 127.0.0.1;
               allow 192.168.233.135;
               deny all;
           }

如果是黑名单形式,不用allow all了,默认就是允许所有,除了限制目录外,也可以根据正则表达式来限制

#插入以下代码
            location ~ .*(abc|image)/.*\.php$
            {
                deny all;
            }

这个可以把访问的URL中带有abc或者image字符串并且是PHP的请求拒绝访问


上传文件的目录禁止解析PHP

#插入以下代码
            if ($http_user_agent ~ 'Spider/3.0|YoudaoBot|Tomato')
            {
                return 403;
            }

~ 为匹配符号,只要user_agent中含有Spider/3.0、YoudaoBot、Tomato,都回被拒绝,return 403为返回403状态码,也可以把它替换为deny all

猜你喜欢

转载自blog.csdn.net/uuicon/article/details/89354754
今日推荐