温馨提示×

centos apache怎样限制访问ip

小樊
32
2026-10-23 12:32:19
栏目: 智能运维

在 CentOS 上通过 Apache(httpd) 限制访问 IP,常用有以下几种方式,按使用场景说明。


一、使用 .htaccess(目录级,最常用)

1. 开启 .htaccess 支持

编辑 Apache 配置文件(如 /etc/httpd/conf/httpd.conf 或虚拟主机配置):

<Directory "/var/www/html">
    AllowOverride All
</Directory>

修改后重启 Apache:

systemctl restart httpd

2. 在网站目录创建 .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

二、在 Apache 配置中直接限制(推荐,性能更好)

1. 限制整个虚拟主机或目录

编辑配置文件(如 /etc/httpd/conf.d/xxx.conf):

<Directory "/var/www/html/admin">
    Require all denied
    Require ip 192.168.1.0/24
</Directory>

2. 限制整个网站

<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

四、禁止特定 IP(黑名单)

Apache 2.4

<RequireAll>
    Require all granted
    Require not ip 192.168.1.50
</RequireAll>

五、测试配置是否正确

httpd -t

输出 Syntax OK 表示正常。


六、常见注意点

  • CentOS 7+ 默认 Apache 2.4,别用 Order/Deny/Allow
  • .htaccess 会影响性能,高并发建议写在配置文件中
  • SELinux 开启时,确认目录权限正常
  • 防火墙(firewalld)也可配合限制:
    firewall-cmd --permanent --add-rich-rule='rule family=ipv4 source address=192.168.1.100 accept'
    firewall-cmd --reload
    

如果你能告诉我:

  • CentOS 版本
  • Apache 版本
  • 想限制的是 整个站点 / 某个目录 / 后台路径

我可以给你一份直接可复制的配置。

0 踩