简体   繁体   中英

Denying access from ip temporary using htaccess

I'm trying to create a little script, that prevents (not preventing, but reduce the effect) of simple ddos attacks. At the moment i'm just including my ddosprotection.php file on every page on my server. If now someone tries to send massive requests on website the script detects this and writes the attackers IP into the htaccess file.

Deny from 1.2.3.4

This should then reduce the effect of an DDOS attack because the attacker doesn't get to the website itself. (Yes i know that the server still needs to process some data, but it's still reducing the impact of a DDOS attack)

My question is now: If some legit user gets on my website and my script is failing to detect him as a legitimate user, he will get banned permanently. Is there a way to only temporary ban a IP adress in htaccess. There shouldn't be any databases connected nor should there be any php script requested when the user tries to connect to the website (this would be nonsense, the attack would be more effective) example:

Deny from 1.2.3.4 before TIMESTAMP

A database does seem the most convenient way to manage this.

But you don't have to run php scripts and query the database on every request: Instead you can add an entry to the database when you block it and run a php script periodically (using cron on Linux for example) to clean up the expired entries and regenerate the .htaccess file. That would also avoid an ever-growing .htaccess file with duplicate ip addresses.

Apart from that you should try to avoid the web-server entirely for blocked entries by writing rules directly to the firewall instead of to an .htaccess file.

Worked this up for you using mod_rewrite and server environment variables:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REMOTE_ADDR} ^1\.2\.3\.4
    RewriteCond %{TIME} <20160827085500
    RewriteRule ^(.*)$ - [F,L]
</IfModule>

Explanation:

  • Make sure mod_rewrite is installed and enabled.
  • If ip address is 1.2.3.4 and server time is before 2016-08-27 8:55:00, redirect to forbidden page.

You'll need to know your server time to calculate the ban time and just add 5 minutes or whatnot. If you're not sure, you can get your server time with php in that format like this:

echo date('Ymdhis');

Now suppose you want to ban the ip for 5 minutes you could do:

date('Ymdhis', strtotime('+5 minutes'))

And use the output in your .htaccess.

You can read more about Time-Dependent Rewriting .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM