Apache配置中如何批量拦截所有python-requests类型的攻击爬虫?
解决Apache批量拦截python-requests爬虫的配置问题
错误原因
你用Require expr %{HTTP_USER_AGENT} !~ 'python-requests'报错,是因为Apache的Require expr语法中,正则匹配的模式需要用**斜杠/**包裹,而非单引号。单引号会被识别为正则模式的一部分,导致语法解析失败。
两种可行的解决方案
方案1:正则匹配(推荐)
用正则匹配所有包含python-requests的User-Agent,替换原来所有单独版本的拦截规则,配置如下:
<RequireAll> Require all granted Require expr %{HTTP_USER_AGENT} != 'Go-http-client/1.1' Require expr %{HTTP_USER_AGENT} != 'Go-http-client/2.0' Require expr %{HTTP_USER_AGENT} != 'Custom-AsyncHttpClient' Require expr %{HTTP_USER_AGENT} != 'l9explore/1.2.2' # 批量拦截所有python-requests爬虫 Require expr %{HTTP_USER_AGENT} !~ /python-requests/ </RequireAll>
方案2:通配符匹配(更直观)
如果不想用正则,也可以用strmatch函数做通配符匹配,效果一致:
<RequireAll> Require all granted Require expr %{HTTP_USER_AGENT} != 'Go-http-client/1.1' Require expr %{HTTP_USER_AGENT} != 'Go-http-client/2.0' Require expr %{HTTP_USER_AGENT} != 'Custom-AsyncHttpClient' Require expr %{HTTP_USER_AGENT} != 'l9explore/1.2.2' # 批量拦截所有python-requests爬虫 Require expr !strmatch(%{HTTP_USER_AGENT}, '*python-requests*') </RequireAll>
验证与生效
修改配置后,先执行apachectl configtest验证语法是否正确,无报错后重启Apache服务即可生效。
补充:mod_rewrite替代方案
如果上述方法不适用(比如Apache版本过低),也可以用mod_rewrite实现拦截,在.htaccess或主配置中添加:
RewriteEngine On # 拦截python-requests爬虫 RewriteCond %{HTTP_USER_AGENT} python-requests [NC] RewriteRule ^ - [F,L] # 其他需要拦截的UA规则 RewriteCond %{HTTP_USER_AGENT} ^Go-http-client/1\.1$ [NC] RewriteRule ^ - [F,L] RewriteCond %{HTTP_USER_AGENT} ^Go-http-client/2\.0$ [NC] RewriteRule ^ - [F,L] RewriteCond %{HTTP_USER_AGENT} ^Custom-AsyncHttpClient$ [NC] RewriteRule ^ - [F,L] RewriteCond %{HTTP_USER_AGENT} ^l9explore/1\.2\.2$ [NC] RewriteRule ^ - [F,L]
内容的提问来源于stack exchange,提问作者Alain Bartolo
相关产品推荐
相关产品推荐

