Apache .htaccess中拒绝恶意访问的rewrite规则
如果是nginx请点击:Nginx如何屏蔽IP、IP段访问网站。
需要说明的是,如果你启用了CDN服务,需要正确识别CDN的IP,腾讯云会给出回源的IP列表,不要将它们屏蔽了,否则你的网站会因为无法回源导致无法访问。
在apache中拒绝IP列表
在/etc/apache2/中新建文件banlist.conf,这里可以填写IP段或IP详细地址。
<RequireAll>
Require all granted
Require not ip 113.219.202.0/24
Require not ip 122.246.31.0/24
Require not ip 219.144.89.0/24
Require not ip 219.144.88.0/24
Require not ip 172.71.223.0/24
</RequireAll>
然后在.htaccess(细分控制)或apache2.conf(全局控制)添加Include /etc/apache2/banlist.conf
<Directory /mnt/xxx.com/public_html/>
...
Include /etc/apache2/banlist.conf
</Directory>拒绝恶意请求
恶意扫描的请求会加大服务器负担,需要在apache端直接屏蔽掉,注意项目入口文件index.php排除在外:
将下面内容保存为.conf文件
<IfModule mod_rewrite.c>
RewriteEngine On
# Allow only the main entry file (index.php)
RewriteCond %{REQUEST_URI} !^/index\.php$ [NC]
# 0. Block direct access to other .php files
RewriteCond %{REQUEST_URI} \.php$ [NC]
RewriteRule ^ - [F,L]
# 1. Deny access to WordPress-related paths
RewriteCond %{REQUEST_URI} ^/(wp-(json|admin|login|content|includes)) [NC]
RewriteRule ^ - [F,L]
# 2. Block .sql files and related patterns
RewriteCond %{REQUEST_URI} \.(sql\.(tar|gz)|backup|dump|db|database)\.sql$ [NC]
RewriteRule ^ - [F,L]
# 3. Block specific query strings used in malicious scans
RewriteCond %{QUERY_STRING} (eval\(|base64_decode\(|union.*select|concat\(|load_file\(|outfile) [NC,OR]
RewriteCond %{QUERY_STRING} (cmd|exec|system|passthru|shell_exec|base64) [NC]
RewriteRule ^ - [F,L]
# 4. Deny access to sensitive files
RewriteCond %{REQUEST_URI} (\.git|\.svn|\.env|\.log|\.bak|\.old|\.zip|\.tar|composer\.(json|lock)|phpinfo\.php) [NC]
RewriteRule ^ - [F,L]
</IfModule>然后在<VirtualHost>中include进去
<IfModule mod_rewrite.c>
Include /etc/apache2/bad-requests.conf
</IfModule> 提示:修改apache配置文件在重启服务之前一定要apache2ctl configtest检查语法。