【Nginx】Nginx安全加固之阻止user-agent的恶意访问
当我们使用网络浏览器(比如:Fire-fox、Google Chrome、Microsoft Edge)访问某个网站页面的时候,浏览器的 agent 信息就会被记录,并传递给服务端。如果服务端的软负载策略中恰好又使用 $http_user_agent 参数记录了客户端的 user-agent 信息,那么,我们就可以在服务端的业务访问日志中获取到类似下面的信息记录:
Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/1xx.0.0.0 Safari/537.36 Edg/147.0.3xxx.xx
当然,上面的情况是正常的用户请求。而对于那些目的在于爬取页面信息、恶意扫描服务器的工具发起的页面访问请求,我们肯定是不希望看见的。这个时候,我们就可以在前端的 nginx 负载中,通过增加一些访问拦截策略来阻止恶意访问。
关于Nginx的map模块
Syntax: map string $variable { ... }
Default: —
Context: http
通过上面的说明,我们可以知道,map 模块必须配置在 http{} 配置块中。
好了,下面我们来做一个简单的测试,我们在已经安装好的nginx的配置文件的http{}块中,增加下面的一段配置:
http {
。。。。。。省略一万行配置。。。。。。
# 定义非法 Agent 过滤规则
map $http_user_agent $blockedagent {
default 0;
~*python-requests 1;
}
再在server{}块中增加下面的 if() 判断:
server {
listen 8081;
server_name 192.168.223.199;
。。。。。。省略一万行配置。。。。。。
# 拦截非法User-Agent
if ($blockedagent) {
return 403;
}
意思就是,如果用户的agent与 python-requests 匹配(前面的~*说明这里的字符串匹配不区分大小写),就给用户返回403的http代码。
配置完成后,对nginx的配置进行格式校验和热加载。
[app@vm-localsystem conf]$ ../sbin/nginx -t
nginx: the configuration file /data/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /data/nginx/conf/nginx.conf test is successful
[app@vm-localsystem conf]$ ../sbin/nginx -s reload
然后我们来测试正常访问和访问拦截的效果:
1)正常访问,可以发现正常返回了nginx的欢迎页面(index.html)。
[app@vm-localsystem conf]$ curl -l -A "Microsoft Edge/109.0.xxx.xx" http://192.168.223.199:8081/
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>
<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>
<p><em>Thank you for using nginx.</em></p>
</body>
</html>
备注:使用 -A 参数来指定本次请求使用的user-agent信息
访问拦截效果,可以看见服务端返回了 403 禁止访问的页面。
[app@vm-localsystem conf]$ curl -l -A "Python-requests" http://192.168.223.199:8081/
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx</center>
</body>
</html>
查看nginx的访问日志,我们也可以得到与上面请求结果一致的日志记录,正常请求返回 200 的 http 代码,而被拦截的请求,返回的则是 403 的 http 代码。
192.168.223.199 - - [21/Apr/2026:11:52:53 +0800] "GET / HTTP/1.1" 200 615 "-" "Microsoft Edge/109.0.xxx.xx" "-"
192.168.223.199 - - [21/Apr/2026:11:57:00 +0800] "GET / HTTP/1.1" 403 146 "-" "Python-requests" "-"
当然,这种被动拦截,在实际的网络安全中,意义并不是很大。如果遇到可以不断修改、更新自己 agent 标识符的恶意程序,这种策略就显得有些捉衿见肘了。
当然,我相信肯定有更好的方式,对这种恶意访问进行高效拦截。
网络安全小白,欢迎留言讨论!~~
参考:
https://nginx.org/en/docs/http/ngx_http_map_module.html#map
更多推荐


所有评论(0)