You may have experience that your website is so slow without any huge traffic-it will be something associated with a bot developed by someone. We have three different options to block abnormal user access in Apache: 1) set a global policy in the Apache httpd.conf 2) set a local policy based on ReWrite Rule in .htaccess. 3) Make a 404 not found error based on the user agent.
How to set a global policy in the Apache /etc/httpd/conf/httpd.conf ?
To set a global policy that blocks access to user agents that don't contain "Mozilla," you can use the following configuration in your httpd.conf
file:
<IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{HTTP_USER_AGENT} !^([^\/]+)\/(\d+)\.(\d+)[^\(]+\(([^\;]+)[^\)]+\) [NC] RewriteRule ^ - [F] </IfModule>
Once you modify the rule in httpd.conf, you should run below commands to take it effect
sudo systemctl restart httpd # on CentOS/RHEL sudo systemctl restart apache2 # on Debian/Ubuntu
Hot to set a local policy for your web application?
You should add below scripts on top of .htaccess in your web application
RewriteEngine On RewriteCond %{HTTP_USER_AGENT} !^([^\/]+)\/(\d+)\.(\d+)[^\(]+\(([^\;]+)[^\)]+\) [NC] RewriteRule ^ - [F]
How do I block in my php code?
You can block abnormal access to your web application by adding below code on top of your code - it will be something like index.php
# block abnormal connection if (!preg_match("/([^\/]+)\/(\d+).(\d+)[^\(]+\(([^\;]+)[^\)]+\)/", getenv('HTTP_USER_AGENT'))) { http_response_code(404); exit; }