在 CentOS 上通过 Apache(httpd) 限制访问 IP,常用有以下几种方式,按使用场景说明。
.htaccess(目录级,最常用).htaccess 支持编辑 Apache 配置文件(如 /etc/httpd/conf/httpd.conf 或虚拟主机配置):
<Directory "/var/www/html">
AllowOverride All
</Directory>
修改后重启 Apache:
systemctl restart httpd
.htaccess例如限制 /var/www/html:
# 禁止所有 IP
Order Deny,Allow
Deny from all
# 允许指定 IP
Allow from 192.168.1.100
Allow from 10.0.0.0/24
✅ Apache 2.2 写法(CentOS 6/早期 7)
Order Deny,Allow
Deny from all
Allow from 203.0.113.5
✅ Apache 2.4 写法(CentOS 7/8/Stream)
Require all denied
Require ip 203.0.113.5
Require ip 192.168.1.0/24
编辑配置文件(如 /etc/httpd/conf.d/xxx.conf):
<Directory "/var/www/html/admin">
Require all denied
Require ip 192.168.1.0/24
</Directory>
<VirtualHost *:80>
ServerName example.com
DocumentRoot /var/www/html
<Location />
Require all denied
Require ip 203.0.113.0/24
</Location>
</VirtualHost>
重启 Apache:
systemctl restart httpd
Require local
或
Require ip 127.0.0.1
<RequireAll>
Require all granted
Require not ip 192.168.1.50
</RequireAll>
httpd -t
输出 Syntax OK 表示正常。
Order/Deny/Allow.htaccess 会影响性能,高并发建议写在配置文件中firewall-cmd --permanent --add-rich-rule='rule family=ipv4 source address=192.168.1.100 accept'
firewall-cmd --reload
如果你能告诉我:
我可以给你一份直接可复制的配置。