You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Apache 2.4 RewriteCond中CondPattern使用系统变量的问题

Apache RewriteCond 实现IP限时封禁的问题

场景与配置说明

已在httpd.conf中通过RewriteEngine实现基础IP黑名单,现需对IP进行限时封禁。为此创建了名为blacklist的映射文件,开发环境示例如下:

10.1.116.135 20221015

其中YYYYMMDD格式的日期表示IP解封的截止日期。

当前配置与问题

httpd.conf配置如下:

RewriteEngine On

RewriteMap    hosts-deny  "txt:/xampp/apache/blacklist"

RewriteCond   "${hosts-deny:%{REMOTE_ADDR}|NOT-FOUND}" "!=NOT-FOUND"
#RewriteCond   "${hosts-deny:%{REMOTE_ADDR}}" "-ge20221011"
RewriteCond   "${hosts-deny:%{REMOTE_ADDR}}" "-ge%{TIME_YEAR}%{TIME_MON}%{TIME_DAY}"
RewriteRule   "^"  "-"  [F]

注释行是使用硬编码日期的有效配置,但改用%{TIME_YEAR}等系统变量时,即使黑名单日期早于当前日期也会返回403。

相关重写日志如下:

map lookup OK: map=hosts-deny[txt] key=10.1.116.135 -> val=20221010,
RewriteCond: input='20221010' pattern='!=NOT-FOUND' => matched,
cache lookup OK: map=hosts-deny[txt] key=10.1.116.135 -> val=20221010
RewriteCond: input='20221010' pattern='-ge%{TIME_YEAR}%{TIME_MON}%{TIME_DAY}' => matched,
forcing responsecode 403 for /dashboards_dev/login.php,

尝试过的方案

  • 尝试使用字符串比较:
    RewriteCond   "${hosts-deny:%{REMOTE_ADDR}}" ">=%{TIME_YEAR}%{TIME_MON}%{TIME_DAY}"
    
    但此配置始终允许访问,即使封禁日期未到。
  • 尝试使用RewriteCond的expr flag时,出现解析错误,提示从"$"开始无法解析。
  • 采用折中方案,仅在封禁日期等于当前日期时返回403,封禁时长为0到24小时:
    RewriteCond ${hosts-deny:%{REMOTE_ADDR}}#%{TIME_YEAR}%{TIME_MON}%{TIME_DAY} ^([^#]+)#(\1)$
    

疑问

如何在RewriteCond的expr语句中正确引用${hosts-deny:%{REMOTE_ADDR}}值,以及CondPattern中使用系统变量的正确语法?

内容的提问来源于stack exchange,提问作者Sharq

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 12:31:05