常见服务器环境中“设置拦截对应请求头”的方式
下面给出常见环境中“设置拦截对应请求头”的方式,可按需要选择使用。整个说明避免出现代词。
1. Nginx 拦截某个请求头
用于阻止带有指定 Header 的请求继续访问。
示例:拦截带有 X-Blocked: true 的请求
server {
location / {
if ($http_x_blocked = "true") {
return 403;
}
proxy_pass http://backend;
}
}要点:
$http_请求头名用于获取 Header判断后直接
return 403即可拦截
2. Node.js (Express/Middleware) 拦截指定请求头
app.use((req, res, next) => {
const headerValue = req.headers['x-blocked'];
if (headerValue === 'true') {
return res.status(403).send('Forbidden');
}
next();
});要点:
通过
req.headers获取请求头判断后阻断请求链路
3. PHP 拦截指定请求头
$headers = getallheaders();
if (isset($headers['X-Blocked']) && $headers['X-Blocked'] === 'true') {
http_response_code(403);
exit('Forbidden');
}要点:
使用
getallheaders()获取 Header符合条件时直接结束请求
4. 微信小程序的服务端(PHP)拦截小程序请求头
小程序端可以携带请求头:
wx.request({
url: 'https://example.com/api',
header: {
'X-App-From': 'miniapp'
},
success(res) {}
})服务端拦截:
$headers = getallheaders();
if (!isset($headers['X-App-From']) || $headers['X-App-From'] !== 'miniapp') {
http_response_code(403);
exit('非法来源');
}5. 如果需要“只允许某些请求头通过”
可使用白名单方式:
$allowedHeaders = ['X-App-From', 'Token', 'Content-Type'];
foreach (getallheaders() as $key => $val) {
if (!in_array($key, $allowedHeaders)) {
http_response_code(403);
exit('请求头不允许');
}
}下面给出一套“拦截这类异常 UA(User-Agent)请求”的完整方案,并适配常见服务器环境。
一、Nginx 方式(最常用)
1. 拦截伪造 UA(含 Mozi、MOZi 等)
server {
location / {
if ($http_user_agent ~* "(Mozi11a|MOZi1la|Mozi1|M0zi)") {
return 403;
}
proxy_pass http://backend;
}
}说明:
~*表示忽略大小写正则匹配将可疑 UA 特征写入括号内即可扩展
2. 拦截异常请求路径
例如 /index.htm1(最后一位是数字,不正常)
if ($request_uri ~* "index\.htm1") {
return 403;
}3. 拦截没有 UA 或 UA 过短的可疑程序扫描
if ($http_user_agent = "") { return 403; }
if ($http_user_agent ~ "^.{0,20}$") { return 403; }4. 拦截高频 IP
可将频繁攻击的 IP 加入 blacklist.conf:
deny 116.29.182.158; deny 113.77.121.195;
加载方式:
include /etc/nginx/blacklist.conf;
二、Apache 拦截规则
RewriteEngine On
# User-Agent 拦截
RewriteCond %{HTTP_USER_AGENT} "Mozi11a|MOZi1la|Mozi1" [NC]
RewriteRule ^.* - [F]
# 异常路径
RewriteCond %{REQUEST_URI} "index\.htm1" [NC]
RewriteRule ^.* - [F]三、PHP 项目内的拦截(适合小程序后端)
放在入口文件 index.php 顶部:
$ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
$badUaPatterns = [
'Mozi11a',
'MOZi1la',
'Mozi1',
'M0zi',
];
foreach ($badUaPatterns as $pattern) {
if (stripos($ua, $pattern) !== false) {
http_response_code(403);
exit('Forbidden');
}
}
// 异常路径拦截
$uri = $_SERVER['REQUEST_URI'] ?? '';
if (strpos($uri, 'index.htm1') !== false) {
http_response_code(403);
exit('Forbidden');
}四、推荐的“综合拦截策略”
适合长期安全维护:
| 项目 | 建议策略 |
|---|---|
| UA 异常 | 使用正则拦截伪造 UA |
| 路径异常 | 拦截带数字替换后缀、奇怪字符的 URL |
| 无 UA/UA 过短 | 拦截 |
| IP 黑名单 | 自动加入高频扫描 IP |
| 添加 Fail2Ban | 自动封禁暴力扫描 |
1. UA 中出现:Chrome/134.0.0.0(异常版本号)
实际 Chrome 发布版本远未到 134,大量僵尸网络与扫描器使用该伪造版本号。
2. UA 前半段均包含假冒信息
如:
Mozi11a/5.0MOZi1la/5.0Mozi1la/5.0M0zi11a/5.0
这是典型 Mozi 僵尸网络(Mozi Botnet) 特征。
3. 部分请求路径异常
例如:
/index.html1/index.htm1
属于扫描器探测目录漏洞的行为。
二、基于这些特征的精准拦截(Nginx)
以下规则可直接精准拦截截图中所有恶意请求,避免误伤正常访问。
① 拦截 UA 中包含 Chrome/134.0.0.0
if ($http_user_agent ~* "Chrome/134\.0\.0\.0") {
return 403;
}② 拦截 Mozi 系列假 UA
if ($http_user_agent ~* "(Mozi11a|MOZi1la|Mozi1la|M0zi|Mozila)") {
return 403;
}③ 拦截异常路径 index.htm1 / index.html1
if ($request_uri ~* "index\.htm1|index\.html1") {
return 403;
}④ 拦截没有 Referer、没有 Cookie 的伪浏览器扫描器(可选)
真实浏览器一般不会完全空 Referer + 空 Cookie。
if ($http_referer = "") {}
if ($http_cookie = "") {}
return 403;
}(如担心误伤,可不启用)
三、综合封禁示例(可直接复制使用)
# 拦截 Chrome/134 假浏览器
if ($http_user_agent ~* "Chrome/134\.0\.0\.0") {
return 403;
}
# 拦截 Mozi 僵尸网络 UA
if ($http_user_agent ~* "(Mozi11a|MOZi1la|Mozi1la|M0zi|Mozila)") {
return 403;
}
# 拦截异常扫描路径
if ($request_uri ~* "index\.htm1|index\.html1") {
return 403;
}完整的 Nginx 安全规则模板(含 SQL 注入、扫描、攻击拦截)
下面是一份可直接复制到生产环境的 Nginx 安全规则模板,覆盖常见的 SQL 注入、XSS、LFI、扫描器识别、异常 UA、速率限制、IP 黑白名单、URI 长度限制、禁用危险方法等防护项。配合 fail2ban 或 ModSecurity 可进一步增强防护能力。
说明:生产环境中建议逐步上线、先在测试环境验证规则的误杀率,并结合访问日志微调正则与阈值。
全局建议(nginx.conf 中 http {} 部分)
# nginx.conf(片段)
user nginx;
worker_processes auto;
worker_rlimit_nofile 65536;
events {
worker_connections 4096;
use epoll;
}
http {
include mime.types;
default_type application/octet-stream;
# 日志格式(便于 fail2ban / 分析)
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" "$request_time"';
access_log /var/log/nginx/access.log main;
error_log /var/log/nginx/error.log warn;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# 缓存、超时等
client_body_timeout 30s;
client_header_timeout 30s;
client_max_body_size 20m;
# 限制 URI 长度与头部长度(防止缓冲区耗尽)
large_client_header_buffers 4 16k;
################################################################
# 速率限制:按 IP 限制请求速率(视业务调节)
limit_req_zone $binary_remote_addr zone=req_zone:10m rate=10r/s;
limit_conn_zone $binary_remote_addr zone=conn_zone:10m;
################################################################
# SQLi / XSS / LFI 简易规则(基于正则) - 使用 map 提高性能
# map 会在请求阶段评估,避免频繁 if 的性能问题
map $request_uri $block_sqli {
default 0;
~*("|\b(union(\s+all)?\s+select)\b) 1;
~*('\s*or\s*'|'\s*like\s*'|--\s|/\*.*\*/|;--|;|drop\s+table) 1;
~*(\b(select|insert|update|delete|sleep|benchmark)\b.*\b(from|into|where)\b) 1;
~*(\bconcat\(|\bload_file\s*\(|\binformation_schema\b) 1;
}
map $request_uri $block_xss {
default 0;
~*("<script|javascript:|%3Cscript%3E|onerror=|onload=|<img|document\.cookie|window\.location)") 1;
}
map $request_uri $block_lfi {
default 0;
~*(\.\./|\.\.\\|/etc/passwd|/proc/self/environ|php://input) 1;
}
# 组合到单一变量(便于一致拦截)
map "$block_sqli|$block_xss|$block_lfi" $block_any {
default 0;
~*1 1;
}
################################################################
# 可疑 UA / 伪造浏览器(示例包含 Mozi、Chrome/134 等)
map $http_user_agent $block_ua {
default 0;
~*(Mozi11a|MOZi1la|Mozi1la|M0zi|Mozila|Chrome/134\.0\.0\.0) 1;
"" 1; # 空 UA 拦截(视情况启用/禁用)
}
################################################################
# 白名单(常用内部 IP 或可信 IP 列表)
# 可以把信任 IP 放到一个文件,便于维护
geo $trusted_ip {
default 0;
127.0.0.1/32 1;
10.0.0.0/8 1;
192.168.0.0/16 1;
}
include /etc/nginx/conf.d/security_blacklist.conf; # 外部黑名单,按需维护
################################################################
# server 配置放在 conf.d 或 sites-enabled
include /etc/nginx/conf.d/*.conf;
}单站点安全 server 示例(conf.d/site-secure.conf)
server {
listen 80;
server_name example.com www.example.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl http2;
server_name example.com www.example.com;
ssl_certificate /etc/ssl/certs/example.crt;
ssl_certificate_key /etc/ssl/private/example.key;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
root /var/www/html;
index index.html index.php;
# 速率限制与连接限制应用
limit_req zone=req_zone burst=20 nodelay;
limit_conn zone=conn_zone 10;
# 先行快速拦截(map 产生的变量)
if ($trusted_ip = 0) {
if ($block_any = 1) {
return 403;
}
if ($block_ua = 1) {
return 403;
}
}
# 拦截常见扫描器特征
if ($request_uri ~* "(?:/index\.htm1|/index\.html1|/phpmyadmin|/pma/|/xmlrpc.php|/wp-login.php|/manager/html)") {
return 403;
}
# 拦截可疑 Method
if ($request_method !~ ^(GET|POST|HEAD)$) {
return 405;
}
# 拦截含 NULL 字节或长 URI
if ($request_uri ~ "\0") {
return 400;
}
if ($request_uri ~ "^.{0,2048}$" ) { }
# 注:可用 ngx_http_core_module 的 large_client_header_buffers 控制头部长度
# 拦截异常 UA
if ($http_user_agent ~* "(curl|wget|python-requests|libwww-perl| ^$)") {
# 注意:此处可能误伤 API 客户端,根据实际业务酌情调整
return 403;
}
# 黑名单文件包含(黑名单中写 deny IP;)
include /etc/nginx/blacklist.conf;
# 静态资源优化与安全头
location ~* \.(?:css|js|jpg|jpeg|gif|png|ico|svg|woff2?)$ {
expires 7d;
add_header Cache-Control "public";
try_files $uri =404;
}
# 入口 PHP 保护(示例为 PHP-FPM)
location ~ \.php$ {
fastcgi_pass unix:/run/php/php-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
# 防止直接访问敏感文件
set $rule_1 0;
if ($request_uri ~* "(\.env|config\.php|wp-config\.php|composer\.json)") {
set $rule_1 1;
}
if ($rule_1 = 1) {
return 403;
}
}
# 禁止目录浏览
location / {
try_files $uri $uri/ /index.php?$query_string;
}
# 返回自定义错误页
error_page 403 /403.html;
location = /403.html {
internal;
root /var/www/errors;
}
# 记录被拦截的请求(便于后续分析)
access_log /var/log/nginx/access_blocked.log combined if=$block_any;
}blacklist.conf 与 security_blacklist.conf 示例(/etc/nginx/blacklist.conf)
# 黑名单 IP,简单示例 deny 116.29.182.158; deny 113.77.121.195; # 通过 GeoIP/外部脚本动态更新时可写入这里
fail2ban 配合示例(提高自动封禁能力)
/etc/fail2ban/filter.d/nginx-sqli.conf
[Definition] failregex = ^<HOST> -.*"(GET|POST).*((union(\s+all)?\s+select)|concat\(|load_file\(|information_schema|benchmark\() [^"]*" [45][0-9][0-9] ignoreregex =
/etc/fail2ban/jail.d/nginx-sqli.local
[nginx-sqli] enabled = true port = http,https filter = nginx-sqli logpath = /var/log/nginx/access.log maxretry = 2 bantime = 3600
fail2ban 会根据 access.log 的失败模式自动封禁高频攻击 IP。针对不同攻击类型可再增加多个 filter(xss、lfi、scanner)。
可选:整合 ModSecurity(WAF 规则引擎)
安装 ModSecurity(libmodsecurity)与 nginx 模块(或使用 OpenResty + lua-waf)。
加载 OWASP CRS(规则集)以获得更全面的规则库。
使用 ModSecurity 能捕获更复杂的攻击模式并记录详细日志。
示例(配置片段):
# 在 http{} 或 server{} 中
modsecurity on;
modsecurity_rules_file /etc/nginx/modsec/main.conf;自动化黑名单脚本(Shell)示例:把 access.log 中高频恶意 UA/IP 加入 blacklist.conf
#!/bin/bash
LOG=/var/log/nginx/access.log
BLACKLIST=/etc/nginx/blacklist.conf
# 从最近 1 小时日志找出访问异常 UA 高频 IP
awk '$0 ~ /Chrome\/134\.0\.0\.0|Mozi11a|MOZi1la|index\.htm1/ {print $1}' $LOG | sort | uniq -c | sort -nr | awk '$1>20 {print $2}' | while read ip; do
if ! grep -q "$ip" $BLACKLIST; then
echo "deny $ip;" >> $BLACKLIST
fi
done
# 重新加载 nginx
nginx -s reload调试与排查建议
首先在测试环境启用规则并观察 access.log 的误杀情况。
逐步放开空 UA、API 客户端等白名单,避免业务被拦截。
使用 fail2ban 或脚本每日统计被拦截请求,调整正则与阈值。
对高价值站点,优先部署 ModSecurity + OWASP CRS。
配合 CDN(Cloudflare、阿里云 CDN 等)可在边缘层减轻探测流量。

- 上一篇:图论中的“单源”和“全源”
- 下一篇:c++中模运算和取余
