Nginx可以通过多种方式实现HTTP请求的内容过滤和防火墙功能。以下是几种常用的方法:
server {
listen 80;
server_name example.com;
# 禁止特定User-Agent
if ($http_user_agent ~* (wget|curl|libwww-perl)) {
return 403;
}
# 阻止特定URL路径
location ~* /(admin|backup|config) {
deny all;
return 404;
}
# 阻止特定查询参数
if ($query_string ~* "union.*select") {
return 403;
}
}
location /secure/ {
# 允许特定IP
allow 192.168.1.0/24;
allow 10.0.0.1;
# 拒绝其他所有
deny all;
}
# 使用OpenResty
wget https://openresty.org/package/centos/openresty.repo
sudo mv openresty.repo /etc/yum.repos.d/
sudo yum install openresty
http {
lua_shared_dict ip_blacklist 10m;
server {
listen 80;
access_by_lua_block {
local blacklist = ngx.shared.ip_blacklist
local client_ip = ngx.var.remote_addr
if blacklist:get(client_ip) then
ngx.exit(ngx.HTTP_FORBIDDEN)
end
-- 检查请求体中的恶意内容
ngx.req.read_body()
local body = ngx.req.get_body_data()
if body and string.find(body:lower(), "<script>") then
blacklist:set(client_ip, true, 3600) -- 封禁1小时
ngx.exit(ngx.HTTP_FORBIDDEN)
end
}
}
}
# 在Ubuntu上安装
sudo apt-get install libmodsecurity3 modsecurity-crs
sudo apt-get install nginx-module-modsecurity
load_module modules/ngx_http_modsecurity_module.so;
http {
modsecurity on;
modsecurity_rules_file /etc/nginx/modsec/main.conf;
server {
listen 80;
location / {
modsecurity on;
proxy_pass http://backend;
}
}
}
http {
map $http_user_agent $bad_user_agent {
default 0;
"~*bot" 1;
"~*spider" 1;
"~*crawler" 1;
}
server {
listen 80;
if ($bad_user_agent) {
return 403;
}
}
}
http {
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
server {
listen 80;
location /login {
limit_req zone=one burst=20 nodelay;
proxy_pass http://backend;
}
}
}
server {
# 阻止SQL注入
set $block_sql_injections 0;
if ($query_string ~ "union.*select.*\(") {
set $block_sql_injections 1;
}
if ($block_sql_injections = 1) {
return 403;
}
# 阻止目录遍历
if ($uri ~* "\.\./") {
return 403;
}
# 阻止XSS攻击
set $block_xss 0;
if ($query_string ~ "<script>") {
set $block_xss 1;
}
if ($block_xss = 1) {
return 403;
}
}
通过以上方法,您可以构建一个强大的HTTP请求过滤和防火墙系统,保护您的Web应用免受多种攻击。