探索建站和运维乐趣

Apache和Nginx禁止ip直接访问的方法

运维服务器的时候,我们是不是会有遇到服务器被特定的IP地址攻击或者扫到?这里我们常用的做法就禁止这个IP或者IP段。这里,我们常用的WEB引擎包括Apache和Nginx,两者的区别就是设置禁止的位置不同,Apache一般是在根目录的.htaccess文件中,Nginx在指定的conf文件配置中全局设置或者当前站点设置。

Apache和Nginx禁止ip直接访问的方法

在这里,整理常见的Apache和Nginx禁止IP的一些用法。

第一、Apache禁止IP直接访问

1、HTTP 禁止IP直接访问

#NameVirtualHost xx.xxx.xxx.xx
<VirtualHost *:80>
ServerName xx.xxx.xxx.xx
ServerAlias xx.xxx.xxx.xx
<Location />
Order Allow,Deny
Deny from all
</Location>
</VirtualHost>

2、HTTPS禁止IP直接访问

#NameVirtualHost xx.xxx.xxx.xx
<VirtualHost *:443>
ServerName xx.xxx.xxx.xx
ServerAlias xx.xxx.xxx.xx
SSLEngine on
SSLProtocol all -SSLv2 -SSLv3
SSLCipherSuite HIGH:!RC4:!MD5:!aNULL:!eNULL:!NULL:!DH:!EDH:!EXP:+MEDIUM
SSLHonorCipherOrder on
SSLCertificateFile /etc/letsencrypt/live/laobuluo.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/laobuluo.com/privkey.pem
SSLCertificateChainFile /etc/letsencrypt/live/laobuluo.com/fullchain.pem
<Location />
Order Allow,Deny
Deny from all
</Location>
</VirtualHost>

第二、Nginx禁止IP直接访问

1、禁止HTTP直接IP访问

server
    {
        listen 80 default;
        return 403;
    }

2、禁止HTTPS直接IP访问

server
{
listen 80 default;
listen 443 default_server;
server_name _;
return 403;
#error_page 404/404.html;
ssl_certificate /etc/letsencrypt/live/laobuluo.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/laobuluo.com/privkey.pem;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers ECDHE-RSA-AES128-GCM- 
SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4:!DH:!DHE;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
error_page 497 https://$host$request_uri;
#SSL-END
}

第三、PHP禁止IP和IP段访问

    <?
    //禁止某个IP
    $banned_ip = array (
    "127.0.0.1",
    //"119.6.20.66",
    "192.168.1.4"
    );
    if ( in_array( getenv("REMOTE_ADDR"), $banned_ip ) )
    {
    die ("您的IP禁止访问!");
    }
    //禁止某个IP段
    $ban_range_low=ip2long("119.6.20.65");
    $ban_range_up=ip2long("119.6.20.67");
    $ip=ip2long($_SERVER["REMOTE_ADDR"]);
    if ($ip>$ban_range_low && $ip<$ban_range_up)
    {
    echo "您的IP在被禁止的IP段之中,禁止访问!";
    exit();
    }
    ?> 

这样,如果我们有需要的话可以设定禁止IP直接访问服务器和网站。

赞(0)
转载保留:老部落 » Apache和Nginx禁止ip直接访问的方法


关注公众号『老蒋朋友圈』

获取更多建站运营运维新知!
互联网创业、前沿技术......