Blocking malicious IPs by .htaccess

One of the best ways to block unwanted traffic from machines and robots or malicious elements is directly from the web server. Therefore, if you use Apache HTTPD or some other web server that supports .htaccess, surely this system will interest you.

People in myip.ms have released script that can help you extend your .htaccess with their IP list that you have on blacklist.

Basically, the software is as follows:

<?php
$separator = "## BLACKLIST IP AUTO ADDED ##";
//
$data_bl = @file_get_contents("http://myip.ms/files/blacklist/htaccess/latest_blacklist.txt");
if ($data_bl === false || !$data_bl) die ();
if (stripos($data_bl, "# Copyright")) $data_bl = substr($data_bl, 0, strripos($data_bl, "# Copyright")) . substr($data_bl, strripos($data_bl, "##############")+16);
//
$data_blu = @file_get_contents("http://myip.ms/files/blacklist/htaccess/latest_blacklist_users_submitted.txt");
if ($data_blu === false || !$data_blu) die ();
$data_blu = substr($data_blu, strripos($data_blu, "##############"));
//
$htaccess = @file_get_contents(rtrim($_SERVER['DOCUMENT_ROOT'], "/ ")."/.htaccess");
if ($htaccess === false) die ();
$htaccess = trim($htaccess);
//
if (stripos($htaccess, $separator) !== false) $htaccess = trim(substr($htaccess, 0, stripos($htaccess, $separator)));
$htaccess .= "nnn" . $separator . "nn" . $data_bl . "nn" . $data_blu;
$htaccess = trim($htaccess) . "n";
//
@file_put_contents(rtrim($_SERVER['DOCUMENT_ROOT'], "/ ")."/.htaccess", $htaccess);

Remember that you must add this PHP within a Cron that must be executed daily.


About this document

This document is regulated by the EUPL v1.2 license, published in WP SysAdmin and created by Javier Casares. Please, if you use this content in your website, your presentation or any material you distribute, remember to mention this site or its author, and having to put the material you create under EUPL license.